Home >Web Front-end >JS Tutorial >4 tips for manipulating JS strings worth knowing
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!
#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.
The split()
method in JavaScript uses the specified delimiter string to split a String
The 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' ]
Through the split()
function a string split by simply join ("")
connect them.
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 in JSON
format. 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}
As you can see from the above code, undefined
will be filtered out in stringify
value, but the null
value 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, [])); // {}
For a huge JSON, passing a long array may affect readability and efficiency. Therefore, the replacement function can be set up and return undefined
for 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}
JSON.stringify()
is specified by Indent (useful in nested blocks) to format JSON
, 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"));
The output format is as follows:
{ "title": "JavaScript 字符串技巧" }
There is also a JSON.parse()
function, which accepts a JSON
string and convert it into a JavaScript object. It also accepts a reviver
function 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 }
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 of 1
).
const countries1 = "China"; const countries2 = "China"; const countries3 = `China`;
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);
The output results are also line-wrapped, as follows:
今天是2021年7月2日, 是个不错的日子!
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.
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
includes function.
true. If it is not included, it will return
false, so you need to use
some functions are used together with
includes, 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
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!