Note: As of 2015, all major browsers (including IE>=9) support String.prototype.trim(). This means that for most use cases simply doing str.trim()
is the best way of achieving what the question asks.
Steven Levithan analyzed many different implementation of trim
in Javascript in terms of performance.
His recommendation is:
function trim1 (str) {
return str.replace(/^ss*/, '').replace(/ss*$/, '');
}
for "general-purpose implementation which is fast cross-browser", and
function trim11 (str) {
str = str.replace(/^s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
"if you want to handle long strings exceptionally fast in all browsers".
References
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…