10 Awesome JS String Tricks You May Not Know About

青灯夜游
Release: 2021-01-08 10:18:29
forward
2080 people have browsed it

10 Awesome JS String Tricks You May Not Know About

Related recommendations: "javascript video tutorial"

We call a character sequencestring. This is one of the basic types found in almost all programming languages. Here are10great 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"
Copy after login

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

padStartandSpadEndmethods, 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***"
Copy after login

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"]
Copy after login

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

lengthattribute.

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

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 (

...), theArray.reversemethod, and theArray.joinmethod.

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

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"
Copy after login

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"
Copy after login

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

splitmethod. Smarties must know this. However, one thing you may not know is thatsplitcan 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"]
Copy after login

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.includesmethod. No regular expressions required.

const text = "Hello, world! My name is Kai!" console.log(text.includes("Kai")); // true
Copy after login

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.startsWithandString.endsWithmethods.

const text = "Hello, world! My name is Kai!" console.log(text.startsWith("Hello")); // true console.log(text.endsWith("world")); // false
Copy after login

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.replacemethod and regular expressions with global flags. Alternatively, you can use the newString.replaceAllmethod. 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 after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!