Home > Web Front-end > JS Tutorial > How to remove spaces from string in JS? js method to remove spaces from string

How to remove spaces from string in JS? js method to remove spaces from string

不言
Release: 2018-08-14 17:04:28
Original
2166 people have browsed it

The content of this article is about how to remove spaces in strings with JS? The method of removing spaces in strings in js has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Method 1:

trim method, this method cannot remove the spaces in the middle of the string

var str = " a b c ";
console.log(str.trim());   //a b c
Copy after login

There is also a trim method in JQuery:

var str = " a b c ";
console.log( $.trim(str));   //a b c
Copy after login

Method 2:

replace method, combined with regular expressions, can remove spaces in different positions.

let str = " a b c ";let reg=/^\s*/g;
//去除全部
let reg2=/^\s*|\s*$/g;
//去除首尾空格
str = str.replace(reg,"");
Copy after login

Related recommendations:

How to get the scroll bar width in js (code example)

How to implement array deduplication in js What? A brief introduction to js array deduplication method

The above is the detailed content of How to remove spaces from string in JS? js method to remove spaces from string. 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