Replace() can be used with regular expressions in js to remove string spaces, for example "replace(/\s /g,"")" to remove all spaces, "replace(/^\s |\s $/g,"")" removes the leading spaces, and "replace(/^\s*/g, "")" removes the left spaces.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript removes spaces
In javascript, you can use the replace() method with regular expressions to remove spaces from strings, which is very efficient.
1. Remove all spaces:
str=str.replace(/\s+/g,"");
2. Remove spaces at both ends:
str=str.replace(/^\s+|\s+$/g,"");
3. Remove left spaces:
str=str.replace( /^\s*/g, "");
4. Remove the right space:
str=str.replace(/(\s*$)/g, "");
can be written as a function like this:
<script type="text/javascript"> function trim(str){ //删除左右两端的空格 return str.replace(/(^\s*)|(\s*$)/g, ""); } function ltrim(str){ //删除左边的空格 return str.replace(/(^\s*)/g,""); } function rtrim(str){ //删除右边的空格 return str.replace(/(\s*$)/g,""); } </script>
[Recommended learning: javascript advanced tutorial]
Related Function introduction: replace() method
Thereplace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
Syntax:
stringObject.replace(regexp/substr,replacement)
Parameters:
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 obtained by replacing the first match or all matches of regexp with replacement.
For more programming related knowledge, please visit: Programming Video! !
The above is the detailed content of How to remove spaces from string in javascript. For more information, please follow other related articles on the PHP Chinese website!