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.
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' ]
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}
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 }
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`;
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
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 theincludes 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
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1
Easy-to-use and free code editor