@param {string} value - The input string to calculate the length of.
@return {number} - The length of the string.
@example
getStringLength('aaaaa') => 5
getStringLength('b') => 1
getStringLength('') => 0
getStringLength() => 0
getStringLength(null) => 0
getStringLength(undefined) => 0
function getStringLength(value) {
return typeof value === "string" ? value.length : 0;
}
@param {string} value - The value to check if it's a string.
@return {boolean} - True if the value is a string, false otherwise.
@example
isString() => false
isString(null) => false
isString([]) => false
isString({}) => false
isString('test') => true
isString(new String('test')) => true
function isString(value) {
if (Array.isArray(value) === true || value == null) {
return false;
}
return value.length >= 0;
}
@param {string} value1 - The first string to concatenate.
@param {string} value2 - The second string to concatenate.
@return {string} - The concatenated string.
@example
concatenateStrings('aa', 'bb') => 'aabb'
concatenateStrings('aa', '') => 'aa'.
concatenateStrings('', 'bb') => 'bb'
function concatenateStrings(value1, value2) {
return value1.concat(value2);
}
@param {string} value - The input string to extract the first character from.
@return {string} - The first character of the string.
@example
getFirstChar('John Doe') => 'J'
getFirstChar('cat') => 'c'
getFirstChar('') => ''
function getFirstChar(value) {
return value.charAt(0);
}
@param {string} value - The input string to remove leading and trailing whitespaces from.
@return {string} - The string with leading and trailing whitespaces removed.
@example
removeLeadingAndTrailingWhitespaces(' Abracadabra') => 'Abracadabra'
removeLeadingAndTrailingWhitespaces('cat ') => 'cat'
removeLeadingAndTrailingWhitespaces('\t\t\tHello, World! ') => 'Hello, World!'
function removeLeadingAndTrailingWhitespaces(value) {
return value.trim();
}
/**
@param {string} value - The input string to remove leading whitespaces from.
@return {string} - The string with leading whitespaces removed.
@example
removeLeadingWhitespaces(' Abracadabra') => 'Abracadabra'
removeLeadingWhitespaces('cat ') => 'cat '
removeLeadingWhitespaces('\t\t\tHello, World! ') => 'Hello, World! '
function removeLeadingWhitespaces(value) {
return value.trimStart();
}
@param {string} value - The input string to remove trailing whitespaces from.
@return {string} - The string with trailing whitespaces removed.
@example
removeTrailingWhitespaces(' Abracadabra') => ' Abracadabra'
removeTrailingWhitespaces('cat ') => 'cat'
removeTrailingWhitespaces('\t\t\tHello, World! ') => '\t\t\tHello, World!'
function removeTrailingWhitespaces(value) {
return value.trimEnd();
}
@param {string} str - The string to repeat.
@param {number} times - The number of times to repeat the string.
@return {string} - The result string.
@example
repeatString('A', 5) => 'AAAAA'
repeatString('cat', 3) => 'catcatcat'
repeatString('', 3) => ''
repeatString('abc', -2) => ''
function repeatString(str, times) {
return times > 0 ? str.repeat(times) : "";
}
@param {string} str - The input string.
@param {string} value - The substring to remove from the string.
@return {string} - The string with the first occurrence of the substring removed.
@example
removeFirstOccurrences('To be or not to be', 'be') => 'To or not to be'.
removeFirstOccurrences('I like legends', 'end') => 'I like legs'.
removeFirstOccurrences('ABABAB', 'BA') => 'ABAB'.
function removeFirstOccurrences(str, value) {
if (str.match(value)) {
const startIndex = str.indexOf(value);
const endIndex = startIndex + value.length;
const startStr = str.slice(0, startIndex);
const endStr = str.slice(endIndex, str.length);
return startStr.concat(endStr);
}
return str;
}
@param {string} str - The input string.
@param {string} value - The substring to remove from the string.
@return {string} - The string with the last occurrence of the substring removed.
@example
removeLastOccurrences('To be or not to be', 'be') => 'To be or not to '.
removeLastOccurrences('I like legends', 'end') => 'I like legs'.
removeLastOccurrences('ABABAB', 'BA') => 'ABAB'.
function removeLastOccurrences(str, value) {
if (str.match(value)) {
const startIndex = str.lastIndexOf(value);
const endIndex = startIndex + value.length;
const startStr = str.slice(0, startIndex);
const endStr = str.slice(endIndex, str.length);
return startStr.concat(endStr);
}
return str;
}
@param {string} str - The input string.
@return {number} - The sum of character codes of the string.
@example
sumOfCodes('My String') => 861 (77 + 121 + 32 + 83 + 116 + 114 + 105 + 110 + 103 = 861)
sumOfCodes('12345') => 495 (9 + 50 + 51 + 52 + 53 = 495)
sumOfCodes('') => 0
sumOfCodes() => 0
function sumOfCodes(str) {
let sum = 0;
if (typeof str === "string") {
for (let i = 0; i <= str.length - 1; i += 1) {
sum += str.charCodeAt(i);
}
}
return sum;
}
@param {string} str - The input string.
@param {string} substr - The substring to check.
@return {boolean} - Returns true if str starts with substr, false otherwise.
@example:
startsWith('Hello World', 'World') => false
startsWith('Hello World', 'Hello') => true
function startsWith(str, substr) {
return str.startsWith(substr);
}
@param {string} str - The input string.
@param {string} substr - The substring to check.
@return {boolean} - Returns true if str starts with substr, false otherwise.
@example:
endsWith('Hello World', 'World') => true
endsWith('Hello World', 'Hello') => false
function endsWith(str, substr) {
return str.endsWith(substr);
}
@param {number} minutes - The number of minutes (non-negative integer).
@param {number} seconds - The number of seconds (non-negative integer).
@return {string} - The time string in the "mm:ss" format.
@example
formatTime(5, 30) => "05:30"
formatTime(1, 15) => "01:15"
formatTime(0, 45) => "00:45"
formatTime(0, 0) => "00:00"
function formatTime(minutes, seconds) {
const m = minutes.toString().padStart(2, "0");
const s = seconds.toString().padStart(2, "0");
return `${m}:${s}`;
}
@param {string} str - The input string.
@return {string} - The string in reverse order.
@example:
reverseString('abcdef') => 'fedcba'
reverseString('12345') => '54321'
function reverseString(str) {
return str.split("").reverse().join("");
}
@param {string} str - The input string.
@return {string} - The string in alphabetical order.
@example:
orderAlphabetically('webmaster') => 'abeemrstw'
orderAlphabetically('textbook') => 'bekoottx'
orderAlphabetically('abc123xyz') => '123abcxyz'
function orderAlphabetically(str) {
return str.split("").sort().join("");
}
@param {string} str - The input string to search within.
@param {string} substring - The substring to check for in the input string.
@returns {boolean} - True if the input string contains the specified substring, false otherwise.
@example
containsSubstring('Hello, World!', 'World') => true
containsSubstring('JavaScript is Fun', 'Python') => false
containsSubstring('12345', '34') => true
function containsSubstring(str, substr) {
return str.includes(substr);
}
Vowels: 'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y'.
@param {string} str - The input string.
@return {number} - The number of vowels in the string.
@example:
countVowels('apple') => 2
countVowels('banana') => 3
countVowels('cherry') => 2
countVowels('aEiOu') => 5
countVowels('XYZ') => 1
function countVowels(str) {
const vowels = /[aeouyi]/gi;
const sum = str.match(vowels);
if (sum === null) {
return 0;
}
return sum.length;
}
https://en.wikipedia.org/wiki/Palindrome
@param {string} str - The input string.
@return {bool} - True if the string is a palindrome, false otherwise.
@example:
isPalindrome('madam') => true
isPalindrome('racecar') => true
isPalindrome('apple') => false
isPalindrome('No lemon, no melon') => true
function isPalindrome(string) {
const str = string
.toLowerCase()
.replaceAll(/[`~!@#$%^&*()_|+\-=?;:'",.<>/]/gi, "");
return (
str.replaceAll(" ", "") ===
str.split("").reverse().join("").replaceAll(" ", "")
);
}
If there are multiple longest words, the function returns the first one encountered.
@param {string} sentence - The input sentence.
@returns {string} - The longest word in the sentence.
@example:
findLongestWord('The quick brown fox') => 'quick'
findLongestWord('A long and winding road') => 'winding'
findLongestWord('No words here') => 'words'
function findLongestWord(sentence) {
const arr = sentence.split(" ");
let longest = arr[0];
for (let i = 0; i <= arr.length - 1; i += 1) {
if (longest.length < arr[i].length) {
longest = arr[i];
}
}
return longest;
}
@param {string} str - The input string.
@return {string} - The string where each word is reversed.
@example:
reverseWords('Hello World') => 'olleH dlroW'
reverseWords('The Quick Brown Fox') => 'ehT kciuQ nworB xoF'
function reverseWords(str) {
const arr = str.split(" ");
const reverseArr = [];
for (let i = 0; i <= arr.length - 1; i += 1) {
reverseArr.push(arr[i].split("").reverse().join(""));
}
return reverseArr.join(" ");
}
@param {string} str - The input string.
@returns {string} - The string with the case of each character inverted.
@example
invertCase('Hello, World!') => 'hELLO, wORLD!'
invertCase('JavaScript is Fun') => 'jAVASCRIPT IS fUN'
invertCase('12345') => '12345'
function invertCase(str) {
const arr = str.split("");
const newArr = [];
for (let i = 0; i <= str.length - 1; i += 1) {
if (arr[i].toLowerCase() === arr[i]) {
newArr.push(arr[i].toUpperCase());
} else {
newArr.push(arr[i].toLowerCase());
}
}
return newArr.join("");
}
Please do not use concatenation, use template string : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
@param {string} firstName - The first name to include in the template.
@param {string} lastName - The last name to include in the template.
@return {string} - The formatted string generated from the template.
@example
getStringFromTemplate('John','Doe') => 'Hello, John Doe!'
getStringFromTemplate('Chuck','Norris') => 'Hello, Chuck Norris!'
function getStringFromTemplate(firstName, lastName) {
return `Hello, ${firstName} ${lastName}!`;
}
@param {string} value - The input value.
@return {string} - The name extracted from the template.
@example
extractNameFromTemplate('Hello, John Doe!') => 'John Doe'
extractNameFromTemplate('Hello, Chuck Norris!') => 'Chuck Norris'
function extractNameFromTemplate(value) {
return value.slice(7, -1);
}
@param {string} str - The input tag.
@return {string} - The tag without the first and last angle brackets.
@example
unbracketTag('
unbracketTag('') => 'span'
unbracketTag('') => 'a'
function unbracketTag(str) {
return str.slice(1, -1);
}
@param {string} str - The input string.
@return {array} - The list of e-mails extracted from the string.
@example
'[email protected];[email protected];[email protected]' => [ '[email protected]',
'[email protected]' ],
'[email protected]' => ['[email protected]']
function extractEmails(str) {
const newStr = str.replaceAll(/;/gi, " ");
const arr = newStr.split(" ");
return arr;
}
See details: https://en.wikipedia.org/wiki/ROT13
@param {string} str - The input string.
@return {string} - The ROT13 encoded string.
@example
'hello' => 'uryyb'
'Why did the chicken cross the road?' => 'Jul qvq gur puvpxra pebff gur ebnq?'
'Gb trg gb gur bgure fvqr!' => 'To get to the other side!'
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
=> 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
function encodeToRot13(str) {
const newArr = [];
let index = 0;
let letterUpper = "";
let letterLower = "";
const arr = str.split("");
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const rot13 = "nopqrstuvwxyzabcdefghijklm";
for (let i = 0; i <= arr.length - 1; i += 1) {
const arrI = arr[i].toLowerCase();
if ("abcdefghijklmnopqrstuvwxyz".includes(arrI)) {
if (arr[i].toLowerCase() === arr[i]) {
index = alphabet.indexOf(arr[i]);
newArr.push(rot13[index]);
} else {
letterLower = arr[i].toLowerCase();
index = alphabet.indexOf(letterLower);
letterUpper = rot13[index];
newArr.push(letterUpper.toUpperCase());
}
} else {
newArr.push(arr[i]);
}
}
return newArr.join("");
}
Playing cards inittial deck inclides the cards in the following order:
'A♣','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣',
'A♦','2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦',
'A♥','2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥',
'A♠','2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠'
(see https://en.wikipedia.org/wiki/Standard_52-card_deck)
Function returns the zero-based index of specified card in the initial deck above.
@param {string} value - The card value.
@return {number} - The zero-based index.
@example
'A♣' => 0
'2♣' => 1
'3♣' => 2
...
'Q♠' => 50
'K♠' => 51
function getCardId(value) {
const codePoint = value.codePointAt(value.length - 1);
let index = 0;
const cards = [
"A",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
];
if (codePoint === 9827) {
index = cards.indexOf(value.slice(0, value.length - 1));
} else if (codePoint === 9830) {
index = cards.indexOf(value.slice(0, value.length - 1)) + 13;
} else if (codePoint === 9829) {
index = cards.indexOf(value.slice(0, value.length - 1)) + 26;
} else {
index = cards.indexOf(value.slice(0, value.length - 1)) + 39;
}
return index;
}