13
Author: Kai
Translator: Front-end Xiaozhi Source: dev

If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

We call a sequence of characters a string . This is one of the basic types found in almost all programming languages. Here is a great trick about JS strings 10 that you may not know yet?

1. How to 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 = '小智'.repeat(3)
consol.log(laughing) // "小智小智小智"

const eightBits = '1'.repeat(8)
console.log(eightBits) // "11111111"

2. How to pad a string to a specified length

Sometimes we want strings to have a certain length. If the string is too short, the remaining space needs to be padded until the specified length is reached.

In the past, the library left-pad was mainly used. However, today we can use the padStart and SpadEnd methods, the choice of which depends on whether to pad the string at the beginning or end of the string.

 // 在开头添加 "0",直到字符串的长度为 8。
const eightBits = '001'.padStart(8, '0')
console.log(eightBits) // "00000001"

//在末尾添加“ *”,直到字符串的长度为5。
const anonymizedCode = "34".padEnd(5, "*")
console.log(anonymizedCode) // "34***"

3. How to split a string into an array of characters

There are various ways to split a string into character arrays, I prefer to use the spread operator ( ... ):

 const word = 'apple'
const characters = [...word]
console.log(characters) // ["a", "p", "p", "l", "e"]

Note that this doesn't always work as expected. See the next tip for more information.

4. How to count characters in a string

The length attribute can be used.

 const word = "apple";
console.log(word.length) // 5

But for Chinese, this method is not very reliable.

 const word = "𩸽"
console.log(word.length) // 2

Kanji 𩸽 return length for 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 surrogate pairs . If you use the length attribute, JS tells you how many code points were used. Therefore, 𩸽(hokke) consists of two code points, returning the wrong value.

Then how to judge it, use the destructuring operation symbol ( ... )

 const word = "𩸽"
const characters = [...word]
console.log(characters.length) // 1

This approach works in most cases, but there are some corner cases. For example, if using emoji, sometimes this length is also wrong. If you really want to calculate the correct length of characters, you have to decompose the word into Grapheme Clusters (Grapheme Clusters) , which is beyond the scope of this article, and will not be explained here.

5. How to reverse the characters in a string

Reversing the characters in a string is easy. Just combine the spread operator ( ... ), Array.reverse method and Array.join method.

 const word = "apple"
const reversedWord = [...word].reverse().join("")
console.log(reversedWord) // "elppa"

As before, there are some edge cases. In the case of edges, it is necessary to first split the word into grapheme clusters .

6. How to capitalize the first letter 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 requires some work.

 let word = 'apply'

word = word[0].toUpperCase() + word.substr(1)

console.log(word) // "Apple"

Another way:

 // This shows an alternative way
let word = "apple";

// 使用扩展运算符(`...`)拆分为字符

const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");

console.log(word); // "Apple"

7. How to split a string on multiple delimiters

Suppose we want to split the string on the delimiter, the first thing that comes to mind is to use the split method, which, Zhimi people must know. However, there is one thing you may not know, that is split can split multiple delimiters at the same time, which can be achieved by using regular expressions:

 // 用逗号(,)和分号(;)分开。

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]

8. How to check if a string contains a specific 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

9. How to check if a string starts or ends with a specific 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

10. How to replace all occurrences of a string

There are multiple ways to replace all occurrences of a string. You can use the String.replace method and regular expressions with global flags. Alternatively, the new String.replaceAll method can be used. 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

Summarize

Strings are one of the most fundamental data types in almost any programming language. At the same time, it is also one of the earliest data types that new developers learn. However, especially in JavaScript, many developers don't know some interesting details about strings. Hope this article is helpful to you.

I'm Xiao Zhi, see you next time.


The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool , Fundebug .

Original: https://dev.to/kais_blog/10-awesome-string-tips-you-might-not-know-about-4ep2

comminicate

If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.


王大冶
68.1k 声望105k 粉丝