In es6, you can use the replace() method to remove all spaces in the string. You only need to use the replace() method with the regular expression "/\s/g" to find all the spaces in the string. Just replace it with a null character; the removal syntax is "String object.replace(/\s/g,"")".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
In es6, you can use the replace() method to remove all spaces in a string.
Thereplace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
stringObject.replace(regexp/substr,replacement)
Parameters | Description |
---|---|
regexp/substr | Required. A RegExp object that specifies the substring or pattern to be replaced. Note that if the value is a string, it is retrieved as a literal text pattern, rather than first being converted to a RegExp object. |
replacement | Required. A string value. Specifies functions for replacing text or generating replacement text. |
Return value
A new string that replaces the first match or all matches of regexp with replacement owned.
Removal method: Use the replace() method with a regular expression to find all spaces and replace them with empty characters.
Regular expression used:
/\s/g
Implementation example:
var str = " hello world " console.log("原字符串:"+str+"!"); var newStr=str.replace(/\s/g,""); console.log("新字符串:"+newStr+"!");
[Related recommendations: javascript video tutorial、webfrontend】
The above is the detailed content of How to remove all spaces from string in es6. For more information, please follow other related articles on the PHP Chinese website!