Strings are one of the most fundamental and important data types in the programming world, and JavaScript is no exception. JavaScript strings are immutable, which is handy for storing text that can be composed of characters, numbers, and Unicode. JavaScript provides a number of built-in functions that allow strings to be created and manipulated in different ways. In this article I will share some elegant techniques for manipulating JavaScript strings.

1. Split the string

The split() method in JavaScript splits a String into an array of substrings using the specified delimiter String, with a specified split String determining the location of each split. Two optional arguments (delimiter and optional limit count) convert a string to an array of characters or substrings, leaving the delimiter unset to return the full string in the array. Separators can take a single character, a string, or even a regular expression. Here is the code to split a string using commas and Spaces using a regular expression:

Const title = "4, JavaScript string techniques "; The console. The log (title. The split (/ / \ s + / + /)); / / [' 4 ', 'JavaScript' and 'string skills'] the console. The log (title. The split (/ \ s + / + /, 2)); // ['4 ', 'JavaScript']Copy the code

Strings split by the split() function can be joined simply by joining (“”).

2. JSON formatting and parsing

JSON is not a javascript-only data type and is widely used for front – and back-end data interaction. The json.stringify () function is used to convert an object to a JSON-formatted string. In general, just take an object as a parameter, as follows:

Const article = {title: "JavaScript string technique ", view: 30000, comments: null, content: undefined,}; const strArticle = JSON.stringify(article); console.log(strArticle); // {"title":"JavaScript string technique ","view":30000,"comments":null}Copy the code

As you can see from the code above, undefined is filtered out in Stringify, but null is not.

Json.stringify () can take two optional arguments, the second of which is a substitute 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 string tips "," Comments ":null} console.log(json.stringify (article, [])); / / {}Copy the code

For a large JSON, passing a long array can affect readability and efficiency. Therefore, you can set the substitution function and return undefined for the key to skip, as follows:

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

The third argument to json.stringify () formats JSON by specifying indentation (useful in nested blocks), passing a number to set the indentation spacing, or even a string to replace Spaces. The following code:

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

The output format is as follows:

{"title": "JavaScript string technique "}Copy the code

There is also a json.parse () function that takes a JSON string and converts it to a JavaScript object. It also accepts a reviver function that intercepts object properties and modifies their values before returning them.

const reviver = (key, value) => (key === "view" ? 0 : value); var jsonString = JSON.stringify(article); var jsonObj = JSON.parse(jsonString, reviver); console.log(jsonObj); // {title: 'JavaScript string technique ', view: 0, comments: null}Copy the code

3. Multi-line strings and embedded expressions

There are three ways to create strings in JavaScript, using single quotes “”, double quotes “”, or backquotes (top left of the keyboard, left of the 1 key).

const countries1 = "China";
const countries2 = "China";
const countries3 = `China`;
Copy the code

The first two are created in much the same way and can be mixed and matched to concatenate or add quoted strings (by using opposite syntax styles), while backquotes can do fancy and powerful things with strings.

Also known as template literals, backquotes are handy when creating multi-line strings and embedded expressions. Here’s how to create a multi-line string using string interpolation in JavaScript:

const year = "2021"; const month = 7; const day = 2; Const detail = 'Today is ${year} ${month} month ${day}. `; console.log(detail);Copy the code

The output is wrapped as follows:

It's July 2, 2021, and it's not a bad day!Copy the code

Except for string literals, any valid expression is allowed in ${}, which can be a function call or expression, or even a nested template.

Tag templates are an advanced form of template literals that allow a function to parse template literals where the embedded expressions are arguments. The following code:

Const title = "JavaScript string technique "; 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); // The title of the article is "JavaScript string techniques", currently read: 30000Copy the code

4. Verify that there are substrings in the string array

It’s easy to find if there are substrings in a JavaScript string. In ES6, you just use the includes function.

Check whether the string exists in the data. Return true if one of the main arrays contains it, false if none. Use some with includes as follows:

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 the code

conclusion

JavaScript string manipulation is common in projects, and the above four techniques are worth learning and applying to real development.