Javascript method to remove spaces in a string: 1. Use the replace() function, syntax "str.replace(' ', '')" or "str.replace(regular expression,"") "; 2. Use trim() function, syntax "str.trim()".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Using JavaScript to remove spaces from a string, there are two methods. One is to use the replace() method to replace spaces (blank characters) with empty strings, and the other is to use the trim() method to remove strings. White space characters at both ends.
replace() method
The use of the replace() method is very simple, just replace it directly.
var str = ' ha ha h haha '; str =str.replace(' ', '');
More, the replace() method supports regular matching.
1. Remove all spaces in the string: str.replace(/\s*/g,"");
2. Remove both ends of the string spaces: str.replace(/^\s*|\s*$/g,"");
3. Remove the spaces on the left side of the string: str.replace(/^\s*/,"");
4. Remove the spaces on the right side of the string: str.replace(/(\s*$)/ g,"");
trim() method
trim() method is used to delete blank characters at both ends of the string. The trim method does not Affects the original string itself and returns a new string.
But this method can only remove the spaces at both ends of the string, but not the spaces in the middle.
var str = " d d b " str =str.trim();
In addition, you can use the trimLeft() method to remove the left space alone, and you can use the trimRight() method to remove the right space alone.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to remove spaces from strings in javascript. For more information, please follow other related articles on the PHP Chinese website!