1. How do I copy a string multiple times
JS strings allow simple repetition; instead of copying strings by hand, we can use the repeat method of strings.
const laughing = 'little wisdom'.repeat(3)
consol.log(laughing) // "I am a fool"
const eightBits = '1'.repeat(8)
console.log(eightBits) / / "11111111"
Copy the code
2. How to fill a string to a specified length
Sometimes we want a string of a certain length. If the string is too short, the remaining space needs to be filled until the specified length is reached. In the past, the library left-pad was used primarily. Today, however, you can use the padStart and SpadEnd methods, depending on whether you populate the string at the beginning or end.
// Add "0" at the beginning until the string length is 8.
const eightBits = '001'.padStart(8.'0')
console.log(eightBits) / / "00000001"
// Add "*" at the end until the string is 5 in length.
const anonymizedCode = "34".padEnd(5."*")
console.log(anonymizedCode) 34 * * * "/ /"
Copy the code
3. How to split a string into an array of characters
There are several ways to split strings into character arrays, and I prefer to use the extension operator (…). :
const word = 'apple'
const characters = [...word]
console.log(characters) // ["a", "p", "p", "l", "e"]
Copy the code
Note that this does not always work as expected. See the next tip for more information.
4. How to calculate characters in a string
You can use the length attribute.
const word = "apple";
console.log(word.length) / / 5
Copy the code
For Chinese, however, this approach is not very reliable.
const word = "𩸽"
console.log(word.length) / / 2
Copy the code
Japanese kanji 𩸽 returns length 2. Why? JS represents most characters as 16-bit code points. However, some characters are represented as two (or more) 16-bit code points, called proxy pairs. If the length attribute is used, JS tells you how many code points are used. Therefore, 𩸽 (hokke) consists of two code points that return the wrong value. How to tell, using deconstruction operation notation (…)
const word = "𩸽"
const characters = [...word]
console.log(characters.length) / / 1
Copy the code
This works in most cases, but there are some extreme cases. For example, if you use emoticons, sometimes this length is also wrong. If you really want to calculate the correct character length, you must decompose the words into Grapheme Clusters, which is beyond the scope of this article and not covered here.
5. How do I reverse characters in a string
It is easy to reverse characters in a string. Simply combine the extension operator (…) , array. reverse, and array. join.
const word = "apple"
const reversedWord = [...word].reverse().join("")
console.log(reversedWord) // "elppa"
Copy the code
Just like before, there are some edge cases. In the case of edges, it is necessary to first split the word into grapheme clusters.
6. How do I capitalize the first character in a string
A very common operation is to capitalize the first letter of a string. While many programming languages have a native way to do this, JS has some work to do.
let word = 'apply'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // "Apple"
Copy the code
Another way:
// This shows an alternative way
let word = "apple";
// Use the extension operator ('... ') split into characters
const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");
console.log(word); // "Apple"
Copy the code
7. How do I split a string on multiple delimiters
If we want to split a string on a separator, the first thing that comes to mind is to use the split method, as I’m sure you know. However, what you may not know is that split can split multiple separators simultaneously, using regular expressions: // with commas (,) and semicolons (;) To separate.
const list = "apples,bananas; cherries"
const fruits = list.split(/ [;] /)
console.log(fruits); // ["apples", "bananas", "cherries"]
Copy the code
8. How do I check if a string contains a particular sequence
String searching is a common task. In JS, you can easily do this using the String.includes method. Regular expressions are not required.
const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true
Copy the code
9. How do I check if a string begins or ends with a particular sequence
To search at the beginning or end of a String, you can use the String.startswith and String.endswith methods.
const text = "Hello, world! My name is Kai!"
console.log(text.startsWith("Hello")); // true
console.log(text.endsWith("world")); // false
Copy the code
10. How do I replace all occurrences of strings
There are several ways to replace all occurrences of strings. You can use the String.replace method and regular expressions with global flags. Alternatively, you can use the new String.replaceAll method. Please note that this new method is not available in all browsers and node.js versions.
const text = "I like apples. You like apples."
console.log(text.replace(/apples/g."bananas"));
// "I like bananas. You like bananas."
console.log(text.replaceAll("apples"."bananas"));
// "I lik
Copy the code