1. Copy a String Multiple Times

The repeat() function creates and returns a new string with the provided number of concatenated copies of the string on which it was called.

// Concatenate "go" 3 times.
const example = "go".repeat(3);

2. Pad a String to a Specific Length

The padStart() function replaces the current string with another string (many times if necessary) until it reaches the specified length. Padding begins at the beginning of the current string.

The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. Padding starts at the end of the current string and continues until the end of the string is reached.

// Add "*" to the end until the string has a length of 5.
const anonymizedUsername = "Jo".padEnd(5, "*");
console.log(anonymizedUsername); // "Jo***"

// Add "0" to the beginning until the string has a length of 8.
const eightBits = "001".padStart(8, "0");
console.log(eightBits); // "00000001"

3. Split a String into an Array of Characters

const word = "codepremix";
const arr = [...word];
console.log(arr); // ["c", "o", "d", "e", "p", "r", "e", "m", "i", "x"]

4. Split a String on Multiple Separators

We can split the string on multiple separators. All you have to do is pass it in the following syntax.

// Let's split on comma (,) and semicolon (;).
const list = "apples,bananas;cherries";
const fruits = list.split(/[,;]/);
console.log(fruits); // ["apples", "bananas", "cherries"]

5. Replace All Occurrences of a String

const text = "JS is the best. I love JS.";

console.log(text.replace(/JS/g, "TS"));
// "TS is the best. I love TS."

console.log(text.replaceAll("JS", "TS"));
// "TS is the best. I love TS."

That’s it in this #quick KB.
Thank you for reading. Happy Coding..!!

Leave a Reply