Home >Web Front-end >Front-end Q&A >javascript string removal
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
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
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
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!