Two methods to remove spaces in a string: 1. Use trim() to remove spaces at the beginning and end of the string, the syntax is "String object.trim()". 2. Using replace(), you can use regular expressions to remove all spaces in the string. The syntax is "String object.replace(/\s/g,"")".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 Method to remove spaces in a string
1. Use trim()--to remove spaces at the beginning and end of a string The trim() method is used to remove the leading and trailing whitespace characters of a string. The whitespace characters include: spaces, tabs, newlines and other whitespace characters.
Note: The trim() method does not change the original string.var str = " hello world " console.log("原字符串:"+str+"!"); var newStr=str.trim(); console.log("新字符串:"+newStr+"!");
2. Use replace()--to remove all spaces in the string
Thereplace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
If you want to use replace() to remove spaces, you can use regular expressions to match the spaces in the string, and then replace them with empty characters''
to remove the spaces.var str = " hello world " console.log("原字符串:"+str+"!"); var newStr=str.replace(/\s/g,""); console.log("新字符串:"+newStr+"!");
[Related recommendations:javascript video tutorial
,web front-end】
The above is the detailed content of How to remove spaces from string in es6. For more information, please follow other related articles on the PHP Chinese website!