trim方法是去除字符串头尾的空格,本文采用正则来处理。
分析:
获取前面的空格:^\s*
获取后面的空格:\s*$
组合起来:^\s*|\s*$
因为要用replace所以用分组来捕获,然后替换掉
最终的正则应该是这样 :/(^\s*)|(\s*$)/g
写实例测试一下
String.prototype.myTrim = function ()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
var str=" hello world ";
console.log(str.myTrim());
打印输出:
hello world
用正则来处理非常的方便,事半功倍!