Home > Article > Web Front-end > How to remove spaces in javascript
Javascript method to remove spaces: 1. Remove all spaces through "str.replace(/\s /g,""); 2. Through "str.replace(/^\s |\s $/g,"");"Remove leading spaces and so on.
The operating environment of this article: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
In JavaScript, you can use the replace() method with regular expressions to remove spaces, which is very efficient.
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.
Let’s take a closer look:
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: js basic tutorial]
The above is the detailed content of How to remove spaces in javascript. For more information, please follow other related articles on the PHP Chinese website!