当前位置:网站首页>js去除字符串空格

js去除字符串空格

2022-06-24 12:59:00 莉兹Liz

js原生方法trim()

str = str.trim();

局限:只能去除字符串两边空格

let str = " 1 2 3 ";
str0 = str.trim();
// "1 2 3"

正则表达式

去除字符串所有空格

str = str.replace(/\s*/g,"");

去除字符串两边空格

str = str.replace(/^\s*|\s*$/g,"");

去除字符串左侧空格

str = str.replace(/^\s*/g,"");

去除字符串右侧空格

str = str.replace(/\s*$/g,"");
str1 = str.replace(/\s*/g,"");
// "123"
str2 = str.replace(/^\s*|\s*$/g,"");
// "1 2 3"
str3 = str.replace(/^\s*/g,"");
// "1 2 3 "
str4 = str.replace(/\s*$/g,"");
// " 1 2 3"

参考

String.prototype.trim()
js去除字符串空格(空白符)

原网站

版权声明
本文为[莉兹Liz]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40138556/article/details/117521608