String#trim(chars)

# Cyril Auburtin (8 years ago)

Like some other languages (ex: python .strip, postgresql trim, ..) I think it would really useful that String.prototype.trim accept a string argument representing the characters to trim (or possibly a regex).

And keep it's default behavior if no argument is passed

'\t Test \n\n'.trim(' \t\n') == 'Test'
# Jordan Harband (8 years ago)

So you want '\t Test \n\n'.replace(/^[ \t\n]+|[ \t\n]+$/g, '') === 'Test'?

# Michael DeByl (8 years ago)

Generally trim() will only operate on the start and end of the strings (also why trimLeft() and trimRight().

All that needs to be done is allow specifying a string or array of characters to trim as an argument – which should not break anything as the trim() method currently accepts nothing. If nothing specified, use [\r, \n, \t, ‘ ‘] – or whatever it currently does as to once again not break anything.

As a sidenote; traditionally trim will use text transforms first from the start, and then from the end of the string. I’m not sure in JS if a regex is faster, or if it even matters overall.

# Michael DeByl (8 years ago)

Generally trim() will only operate on the start and end of the strings (also why trimLeft() and trimRight().

All that needs to be done is allow specifying a string or array of characters to trim as an argument – which should not break anything as the trim() method currently accepts nothing. If nothing specified, use [\r, \n, \t, ‘ ‘] – or whatever it currently does as to once again not break anything.

As a sidenote; traditionally trim will use text transforms first from the start, and then from the end of the string. I’m not sure in JS if a regex is faster, or if it even matters overall.

# Isiah Meadows (8 years ago)

To be clear, trim could easily be implemented like this:

function trim(str) {
    return str.replace(/^\s+|\s+$/g, "")
}

If you need something similar, you can alter that regular expression accordingly to get what you want.

As for performance, if you really get to the point where that becomes your bottleneck, you should really reconsider what you're actually doing.

Isiah Meadows me at isiahmeadows.com