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

How to remove spaces in javascript

藏色散人
Release: 2023-01-03 09:31:44
Original
9181 people have browsed it

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.

How to remove spaces in javascript

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)
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.

Let’s take a closer look:

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: 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!

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