Home  >  Article  >  Web Front-end  >  10 Awesome JS String Tricks You May Not Know About

10 Awesome JS String Tricks You May Not Know About

青灯夜游
青灯夜游forward
2021-01-08 10:14:432199browse

10 Awesome JS String Tricks You May Not Know About

Related recommendations: "javascript video tutorial"

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

1. How to copy a string multiple times

JS strings allow simple duplication. Unlike copying strings manually, we can use the # of the string. ##repeatMethod.

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 a string to have a specific length. If the string is too short, the remaining space needs to be padded until it reaches the specified length.

In the past, the library left-pad was mainly used. However, today we can use the

padStart and SpadEnd methods, which one you choose depends on whether you want to pad the string at the beginning or the end.

// 在开头添加 "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 a character array

There are many ways to split a string into a character array, I prefer to use the spread operator (

...):

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

Note, this does not always work as expected. See the next tip for more information.

4. How to calculate the characters in a string

You can use the

length attribute.

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

But for Chinese, this method is not very reliable.

10 Awesome JS String Tricks You May Not Know About

10 Awesome JS String Tricks You May Not Know About

How to judge? Use the destructuring operator symbol (

...)

10 Awesome JS String Tricks You May Not Know About

This method works in most cases, but there are some edge cases. For example, if you use emoticons, sometimes this length is wrong as well. If you really want to calculate the correct length of characters, you must decompose the word into

Grapheme Clusters, which is beyond the scope of this article and will not be explained here.

5. How to reverse characters in a string

Reversing characters in a string is easy. Just combine the spread operator (

...), the Array.reverse method, and the Array.join method.

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

As before, there are also some edge cases. When encountering edge cases, 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 method:

// 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 multiple delimiters When splitting a string, the first thing that comes to mind is to use the

split method. Smarties must know this. However, one thing you may not know is that split can split multiple delimiters at the same time. This can be achieved using regular expressions:

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

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

8. How to check a string Searching for strings containing a specific sequence

is a common task. In JS you can do this easily using the

String.includes method. No regular expressions 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

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 many ways to replace all occurrences of a string. 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

Summary

Strings are one of the most basic data types in almost all programming languages. 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.

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

Author: Kai

Translation address: https://segmentfault.com/a/1190000038542256

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of 10 Awesome JS String Tricks You May Not Know About. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete