javascript 字符串去空格

1、正则去空格

a.去掉字符串中所有空格

"   hello world   ".replace(/\s+/g,"");//helloworld

b.去掉字符串左边空格

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

c.去掉字符串右边空格

var str = "   hello world   ".replace(/\s*$/g,"");//...hello world

d.去掉字符串左边和右边空格

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

可以给String的原型添加方法

String.prototype.Trim = function(){

  return this.replace(/(^s*)|(\s*$)/g,'');

}
String.prototype.LTrim = function(){

  return this.replace(/^s*/g,'');

}
String.prototype.RTrim = function(){

  return this.replace(/\s*$/g,'');

}

然后使用

"   hello world".LTrim();
//hello world
"hello world  ".RTrim();
//hello world
"  hello world  ".Trim();
//hello world

 

posted @ 2017-09-15 14:50  wjwdive  阅读(193)  评论(0编辑  收藏  举报