4 tips for manipulating JS strings worth knowing

青灯夜游
Release: 2021-07-21 09:33:07
forward
1566 people have browsed it

String is one of the most basic and important data types in the programming world, and JavaScript is no exception. The following article will share with you 4 elegant techniques for manipulating JavaScript strings. Come and collect them!

4 tips for manipulating JS strings worth knowing

#JavaScript strings are immutable and convenient for storing text that can be composed of characters, numbers, and Unicode. JavaScript provides many built-in functions that allow strings to be created and manipulated in different ways. Let’s take a look at these 4 elegant techniques for manipulating JavaScript strings.

1. Split the string

Thesplit()method in JavaScript uses the specified delimiter string to split aStringThe object is split into an array of substrings, and a specified split string is used to determine the position of each split. There are two optional parameters (delimiter and optional limit count) to convert the string to an array of characters or substrings. Not setting the delimiter will return the complete string in the array. Delimiters can be single characters, strings, or even regular expressions. Here is the code that will split a string using commas and spaces using regular expressions:

const title = "4个,JavaScript 字符串技巧"; console.log(title.split(/[\s+,/]+/)); // [ '4个', 'JavaScript', '字符串技巧' ] console.log(title.split(/[\s+,/]+/, 2)); // [ '4个', 'JavaScript' ]
Copy after login

Through thesplit()function a string split by simplyjoin ("")connect them.

2. JSON formatting and parsing

JSON is not a JavaScript-only data type and is widely used for front-end and back-end data interaction.JSON.stringify()The function is used to convert an object into a string inJSONformat. Usually, just pass the object as a parameter, as shown below:

const article = { title: "JavaScript 字符串技巧", view: 30000, comments: null, content: undefined, }; const strArticle = JSON.stringify(article); console.log(strArticle); // {"title":"JavaScript 字符串技巧","view":30000,"comments":null}
Copy after login

As you can see from the above code,undefinedwill be filtered out instringifyvalue, but thenullvalue does not.

JSON.stringify()Can accept two optional parameters, the second parameter is a replacer in which you can specify an array of keys to print or a function to clear them. The following code:

console.log(JSON.stringify(article, ["title", "comments"])); // {"title":"JavaScript 字符串技巧","comments":null} console.log(JSON.stringify(article, [])); // {}
Copy after login

For a huge JSON, passing a long array may affect readability and efficiency. Therefore, the replacement function can be set up and returnundefinedfor the keys to be skipped, as in the following code: The third parameter of

const result = JSON.stringify(article, (key, value) => key === "title" ? undefined : value ); console.log(result); // {"view":30000,"comments":null}
Copy after login

JSON.stringify()is specified by Indent (useful in nested blocks) to formatJSON, you can pass a number to set the indent spacing, or even a string to replace spaces. The following code:

console.log(JSON.stringify(article, ["title"], "\t"));
Copy after login

The output format is as follows:

{ "title": "JavaScript 字符串技巧" }
Copy after login

There is also aJSON.parse()function, which accepts aJSONstring and convert it into a JavaScript object. It also accepts areviverfunction that can intercept object properties and modify property values before returning the value.

const reviver = (key, value) => (key === "view" ? 0 : value); var jsonString = JSON.stringify(article); var jsonObj = JSON.parse(jsonString, reviver); console.log(jsonObj); // { title: 'JavaScript 字符串技巧', view: 0, comments: null }
Copy after login

3. Multi-line strings and embedded expressions

There are three ways to create strings in JavaScript, you can use single quotes'', double quotation mark""or backtick mark (top left of the keyboard, left key of1).

const countries1 = "China"; const countries2 = "China"; const countries3 = `China`;
Copy after login

The first two creation methods are basically the same, and can be mixed and matched to concatenate or add quoted strings (by using the opposite syntax style), while backticks can do fancy and powerful things with strings operate.

Backticks are also called template literals. Backticks are convenient when creating multi-line strings and embedded expressions. The following is the code for how to use string interpolation to create a multi-line string in JavaScript:

const year = "2021"; const month = 7; const day = 2; const detail = `今天是${year}年${month}月${day}日, 是个不错的日子!`; console.log(detail);
Copy after login

The output results are also line-wrapped, as follows:

今天是2021年7月2日, 是个不错的日子!
Copy after login

In addition to string literals, in ## Any valid expression is allowed in #${}, it can be a function call or expression, or even a nested template.

Tagged templates are an advanced form of template literals that allow the template literal to be parsed using a function in which embedded expressions are parameters. The following code:

const title = "JavaScript 字符串技巧"; const view = 30000; const detail = (text, titleExp, viewExp) => { const [string1, string2, string3] = [...text]; return `${string1}${titleExp}${string2}${viewExp}${string3}`; }; const intro = detail`本文的标题是《${title}》,当前阅读量是: ${view}`; console.log(intro); // 文的标题是《JavaScript 字符串技巧》,当前阅读量是:30000
Copy after login

4. Verify whether a substring exists in a string array

Finding whether a substring exists in a JavaScript string is an easy thing. In ES6, you only need to use the

includesfunction.

But you need to verify whether the string is stored in the data. If one of the items in the main array is included, it will return

true. If it is not included, it will returnfalse, so you need to usesomefunctions are used together withincludes, as shown in the following code:

const arrayTitles = ["Javascript", "EScript", "Golang"]; const hasText = (array, findText) => array.some((item) => item.includes(findText)); console.log(hasText(arrayTitles, "script")); // true console.log(hasText(arrayTitles, "php")); // false
Copy after login

Summary

JavaScript string operations are common in projects Operation, the above four skills are worth learning and applying to actual development.

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of 4 tips for manipulating JS strings worth knowing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
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!