Home  >  Article  >  Web Front-end  >  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

不言
不言Original
2018-08-14 17:04:282083browse

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

There is also a trim method in JQuery:

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

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

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!

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