trim函数的应用:去除字符串头尾空格的。
在 JS 里一般情况下用正则去除字符串头尾空格的 trim 函数的写法为:
String.prototype.trim = function () {
return this.replace(/^[\s\t ]+|[\s\t ]+$/g, '');
}
s = ' this is a trim function test. ';
alert(s.trim().length);
更加完善的写法为:
/**
* trim 性能出现问题的原因;
*「量词限定」将优先匹配。
*「量词限定」在结尾可能会使 JS 的正则引擎不停的回朔,出现递归的一个陷阱,这个递归的深度太深。
*如果字符串更大一点应该会出现栈溢出了。
*多行匹配性能消耗不大,即化简递归深度。
* @param {*} value
*/
// 改良的trim方法
const metaTrim = (value) => {
const s = value.replace(/^[\s\t ]+/g, '');
return s;
};
参考网址:
http://fexteam.gz01.bdysite.com/blog/2014/03/trim-to-regexp-performance/