Trim spaces from start and end of string

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(/^\s\s*/, '').replace(/\s\s*$/, '');
}

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

Leave a Comment