Table of Contents
1. Split the string
2. JSON formatting and parsing
3. Multi-line strings and embedded expressions
4. Verify whether a substring exists in a string array
Home Web Front-end JS Tutorial 4 tips for manipulating JS strings worth knowing

4 tips for manipulating JS strings worth knowing

Jul 16, 2021 am 09:48 AM
javascript string

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

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

Through the split() function a string split by simply join ("") 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 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}
Copy after login

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, [])); // {}
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 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}
Copy after login

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

The output format is as follows:

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

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 }
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 of 1).

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

includes function.

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 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
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to determine whether a Golang string ends with a specified character How to determine whether a Golang string ends with a specified character Mar 12, 2024 pm 04:48 PM

Title: How to determine whether a string ends with a specific character in Golang. In the Go language, sometimes we need to determine whether a string ends with a specific character. This is very common when processing strings. This article will introduce how to use the Go language to implement this function, and provide code examples for your reference. First, let's take a look at how to determine whether a string ends with a specified character in Golang. The characters in a string in Golang can be obtained through indexing, and the length of the string can be

Detailed explanation of the method of converting int type to string in PHP Detailed explanation of the method of converting int type to string in PHP Mar 26, 2024 am 11:45 AM

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

How to intercept a string in Go language How to intercept a string in Go language Mar 13, 2024 am 08:33 AM

Go language is a powerful and flexible programming language that provides rich string processing functions, including string interception. In the Go language, we can use slices to intercept strings. Next, we will introduce in detail how to intercept strings in Go language, with specific code examples. 1. Use slicing to intercept a string. In the Go language, you can use slicing expressions to intercept a part of a string. The syntax of slice expression is as follows: slice:=str[start:end]where, s

How to repeat a string in python_python repeating string tutorial How to repeat a string in python_python repeating string tutorial Apr 02, 2024 pm 03:58 PM

1. First open pycharm and enter the pycharm homepage. 2. Then create a new python script, right-click - click new - click pythonfile. 3. Enter a string, code: s="-". 4. Then you need to repeat the symbols in the string 20 times, code: s1=s*20. 5. Enter the print output code, code: print(s1). 6. Finally run the script and you will see our return value at the bottom: - repeated 20 times.

How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP Mar 04, 2024 am 09:36 AM

Methods to solve Chinese garbled characters when converting hexadecimal strings in PHP. In PHP programming, sometimes we encounter situations where we need to convert strings represented by hexadecimal into normal Chinese characters. However, in the process of this conversion, sometimes you will encounter the problem of Chinese garbled characters. This article will provide you with a method to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP, and give specific code examples. Use the hex2bin() function for hexadecimal conversion. PHP’s built-in hex2bin() function can convert 1

How to check if a string starts with a specific character in Golang? How to check if a string starts with a specific character in Golang? Mar 12, 2024 pm 09:42 PM

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

PHP String Matching Tips: Avoid Ambiguous Included Expressions PHP String Matching Tips: Avoid Ambiguous Included Expressions Feb 29, 2024 am 08:06 AM

PHP String Matching Tips: Avoid Ambiguous Included Expressions In PHP development, string matching is a common task, usually used to find specific text content or to verify the format of input. However, sometimes we need to avoid using ambiguous inclusion expressions to ensure match accuracy. This article will introduce some techniques to avoid ambiguous inclusion expressions when doing string matching in PHP, and provide specific code examples. Use preg_match() function for exact matching In PHP, you can use preg_mat

PHP string manipulation: a practical way to effectively remove spaces PHP string manipulation: a practical way to effectively remove spaces Mar 24, 2024 am 11:45 AM

PHP String Operation: A Practical Method to Effectively Remove Spaces In PHP development, you often encounter situations where you need to remove spaces from a string. Removing spaces can make the string cleaner and facilitate subsequent data processing and display. This article will introduce several effective and practical methods for removing spaces, and attach specific code examples. Method 1: Use the PHP built-in function trim(). The PHP built-in function trim() can remove spaces at both ends of the string (including spaces, tabs, newlines, etc.). It is very convenient and easy to use.

See all articles