String strip() for JavaScript? [duplicate]

String strip() for JavaScript? [duplicate]

This question already has an answer here:

Trim string in JavaScript?

25 answers

What’s a clean and efficient JavaScript implementation to strip leading and trailing spaces from a string?
For example:
” dog”
“dog ”
” dog ”
” dog ”
all get turned into


Solution 1:

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 J-P’s suggestion to combine the regex patterns into one. Also added the global modifier per Christoph’s suggestion.

Took Matthew Crumley’s idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.

Solution 2:

For jquery users, how about $.trim(s)

Solution 3:

Gumbo already noted this in a comment, but this bears repeating as an answer: the trim() method was added in JavaScript 1.8.1 and is supported by all modern browsers (Firefox 3.5+, IE 9, Chrome 10, Safari 5.x), although IE 8 and older do not support it. Usage is simple:

 "  foo\n\t  ".trim() => "foo"

See also:

Related:  How to make HTML element resizable using pure javascript?

Solution 4:

Here’s the function I use.

function trim(s){ 
  return ( s || '' ).replace( /^\s+|\s+$/g, '' ); 

Solution 5:

A better polyfill from the MDN that supports removal of BOM and NBSP:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');

Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string) instead. That being said, if you are targeting an older environment without native .trim() support, you are likely to have more important performance issues to deal with.

Solution 6:

Steven Levithan once wrote about how to implement a Faster JavaScript Trim. It’s definitely worth a look.