Skip to content

My solutions to String tasks with the usage of String methods as part of RS School.

Notifications You must be signed in to change notification settings

sshhevvanna/strings-methods-tasks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 

Repository files navigation

Returns the length of the given string.

@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;
}

Returns true if the value is a string, otherwise returns false.

@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;
}

Returns the result of concatenation of two strings.

@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);
}

Returns the first character of the given string.

@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);
}

Removes leading and trailing whitespace characters from the string.

@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();
}

/**

Removes only leading whitespace characters from the string.

@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();
}

Removes only trailing whitespace characters from the string.

@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();
}

Returns a string that is repeated the specified number of times.

@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) : "";
}

Remove the first occurrence of a substring from a string.

@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;
}

Remove the last occurrence of a substring from a string.

@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;
}

Calculate the sum of character codes of the given string.

@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;
}

Checks if a string starts with a specific substring.

@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);
}

Checks if a string ends with a specific substring.

@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);
}

Returns a time string in the "mm:ss" format.

@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}`;
}

Returns a string in reverse order.

@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("");
}

Returns a string with characters in alphabetical order.

@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("");
}

Checks if a given string contains a specified substring.

@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);
}

Returns the number of vowels in the string.

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;
}

Returns true if the string is a palindrome; otherwise false.

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(" ", "")
);
}

Find the longest word in the sentence.

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;
}

Returns the string where each word is reversed.

@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(" ");
}

Inverts the case of each character in the given string.

@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("");
}

Returns the result of string template and given parameters firstName and lastName.

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}!`;
}

Extracts a name from template string 'Hello, First_Name Last_Name!'.

@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);
}

Remove the first and last angle brackets from tag string

@param {string} str - The input tag.

@return {string} - The tag without the first and last angle brackets.


@example

unbracketTag('

') => 'div'

unbracketTag('') => 'span'

unbracketTag('') => 'a'

function unbracketTag(str) {
return str.slice(1, -1);
}

Extracts e-mails from single string with e-mails list delimited by semicolons

@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]' => ['[email protected]']

function extractEmails(str) {
const newStr = str.replaceAll(/;/gi, " ");
const arr = newStr.split(" ");
return arr;
}

Encode specified string with ROT13 cipher

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("");
}

Returns playid card id.

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;
}

About

My solutions to String tasks with the usage of String methods as part of RS School.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published