JavaScript 清除字符串两端空格

现在大部分浏览器中基本上都支持字符串的 trim 函数,但是为了兼容不支持的浏览器,我们最好还是在 Js 文件中加入以下代码(不需要清除换行符的请删除   制表符删除  ):

 1 if (!String.prototype.trim) {
 2     /*---------------------------------------
 3      * 清除字符串两端空格,包含换行符、制表符
 4      *---------------------------------------*/
 5     String.prototype.trim = function () { 
 6         return this.triml().trimr(); 
 7     }
 8     /*----------------------------------------
 9      * 清除字符串左侧空格,包含换行符、制表符
10      * ---------------------------------------*/
11     String.prototype.triml = function () {
12         return this.replace(/^[s
	]+/g, "");
13     }
14     /*----------------------------------------
15      * 清除字符串右侧空格,包含换行符、制表符
16      *----------------------------------------*/
17     String.prototype.trimr = function () {
18         return this.replace(/[s
	]+$/g, "");
19     }
20 }

如果只需要 trim 函数的,可以只写一个:

1 if (!String.prototype.trim){
2     /*---------------------------------------
3      * 清除字符串两端空格,包含换行符、制表符
4      *---------------------------------------*/
5     String.prototype.trim = function () { 
6         return this.replace(/(^[s
	]+|[s
	]+$)/g, "");
7     }
8     
9 }

使用代码:

var str = " abcd ".trim();

 去除左边空格!

去除 

<script type="text/javascript">
$('.newsList li p').each(function(){
$(this).html($(this).html().replace(/&nbsp;/gi,""));
})
</script>

 包括空格:

replace(/[ ]|[&nbsp;]/gi, '');   

删除空格和&nbsp;

var msg = $(".msg").text().replace(/&nbsp;/g, "").replace(/ /g, "").replace(/s/g, "");
console.log(msg);
原文地址:https://www.cnblogs.com/ghfjj/p/6306348.html