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