Home > Web Front-end > JS Tutorial > How to remove spaces from string in javascript

How to remove spaces from string in javascript

青灯夜游
Release: 2023-01-04 09:34:56
Original
5800 people have browsed it

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.

How to remove spaces from string in javascript

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,"");
Copy after login

2. Remove spaces at both ends:

str=str.replace(/^\s+|\s+$/g,"");
Copy after login

3. Remove left spaces:

str=str.replace( /^\s*/g, "");
Copy after login

4. Remove the right space:

str=str.replace(/(\s*$)/g, "");
Copy after login

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>
Copy after login

[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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template