Home > Web Front-end > JS Tutorial > body text

How to remove spaces from strings in javascript

青灯夜游
Release: 2021-11-03 15:26:32
Original
21696 people have browsed it

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

How to remove spaces from strings in javascript

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!