javascript string removal

王林
Release: 2023-05-22 09:01:07
Original
2497 people have browsed it

Javascript There are three commonly used methods for string removal, namely using the replace() function, using regular expressions and using the trim() function.

1. Use the replace() function

Use the replace() function in a string to delete specified characters or strings in a string. To use the replace() function, you need to pass in two parameters. The first parameter is the character or string that needs to be deleted. The second parameter is the character or string that you want to replace. Pass the second parameter into the empty string. to delete characters or strings.

For example, the following code removes all spaces in the string:

let str = " Hello World ";
str = str.replace(/s+/g, "");
console.log(str); //输出HelloWorld
Copy after login

Use the regular expression /s /g to match all spaces and replace them with null characters The string can be deleted.

2. Use regular expressions

Using regular expressions in strings can also remove specified characters or strings. Similar to using the replace() function to delete a string, you need to use a regular expression for matching.

For example, the following code uses a regular expression to remove all commas in a string:

let str = "a,b,c,d,e,f";
str = str.replace(/,/g, "");
console.log(str); //输出abcdef
Copy after login

Use /,/g in the regular expression to match all commas, Replace it with an empty string to remove it.

3. Use the trim() function

Use the trim() function to remove spaces at both ends of a string. This function has no parameters. You can delete the spaces at both ends by calling this function directly.

For example, the following code removes spaces at both ends of a string:

let str = "  Hello World  ";
str = str.trim();
console.log(str); //输出Hello World
Copy after login

Use the trim() function to easily remove spaces at both ends of a string.

The above are three common methods for Javascript string removal: using the replace() function, using regular expressions and using the trim() function. Which method to use depends on the actual situation.

The above is the detailed content of javascript string removal. For more information, please follow other related articles on the PHP Chinese website!

source:php.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
Popular Tutorials
More>
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!