How to remove spaces from a string by javascript
This article mainly explains "javascript how to remove the space character in the string". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "javascript how to remove the space character in the string".
Javascript to remove the empty space character in the string method: 1, use 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, javascript1.8.5 version, Dell G3 computer.
There are two ways to use JavaScript to remove white space from a string, one is to use the replace () method to replace the space (blank character) with an empty string, and the other is to use the trim () method to remove white space characters at both ends of the string.
Replace () method
The use of the replace () method is very simple, just replace it directly.
Var str = ' h '; str = str.replace (',')
What's more, the replace () method supports regular matching.
1. Remove all whitespace in the string: str.replace (/\ sscratch _ g, ")
two。 Remove the spaces at both ends of the string: str.replace (/ ^\ s * |\ sroomcospacg, "")
3. Remove the space on the left side of the string: str.replace (/ ^\ simpulse, "")
4. Remove the space on the right side of the string: str.replace (/ (\ sblank $) / g, ")
Trim () method
The trim () method is used to delete white space characters at both ends of a string. The trim method does not affect the original string itself. It returns a new string.
But this method can only remove the spaces at both ends of the string, 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 the trimRight () method to remove the right space alone.
Thank you for reading, the above is the content of "javascript how to remove the space characters in the string". After the study of this article, I believe you have a deeper understanding of how javascript removes the space characters in the string, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!