Use this:(用这个:)
if(typeof(String.prototype.trim) === "undefined")
{
String.prototype.trim = function()
{
return String(this).replace(/^s+|s+$/g, '');
};
}
The trim function will now be available as a first-class function on your strings.(装饰函数现在将作为字符串的一等函数提供。) For example:(例如:)
" dog".trim() === "dog" //true
EDIT : Took JP's suggestion to combine the regex patterns into one.(编辑 :采纳了JP的建议,将正则表达式模式组合为一个。) Also added the global modifier per Christoph's suggestion.(还根据Christoph的建议添加了全局修饰符。)
Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it.(重新创建修整功能之前,请听取Matthew Crumley的想法。) This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.(如果客户端使用的JavaScript版本较新,因此具有自己的本机修整功能,则可以这样做。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…