[javascript] Trim spaces from start and end of string

I am trying to find a way to trim spaces from the start and end of the title string. I was using this, but it doesn't seem to be working:

title = title.replace(/(^[\s]+|[\s]+$)/g, '');

Any ideas?

This question is related to javascript regex

The answer is


As @ChaosPandion mentioned, the String.prototype.trim method has been introduced into the ECMAScript 5th Edition Specification, some implementations already include this method, so the best way is to detect the native implementation and declare it only if it's not available:

if (typeof String.prototype.trim != 'function') { // detect native implementation
  String.prototype.trim = function () {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  };
}

Then you can simply:

title = title.trim();

You can use trimLeft() and trimRight() also.

const str1 = "   string   ";
console.log(str1.trimLeft()); 
// => "string   "

const str2 = "   string   ";
console.log(str2.trimRight());
// => "    string"

When the DOM is fully loaded, you can add this to all the text fields. I have never had a situation where I needed to submit leading or trailing space, so doing it all the time globally has worked for me...

$(function() { $('input[type=text]').on('blur', function(){
    $(this).val($.trim($(this).val()));
  });
});

I know this is an old post, but just thought I'd share our solution. In the quest for shortest code (doesn't everyone just love terse regex), one could instead use:

title = title.replace(/(^\s+|\s+$)/g, '');

BTW: I ran this same test through the link shared above blog.stevenlevithan.com -- Faster JavaScript Trim and this pattern beat all the other HANDS down!

Using IE8, added test as test13. The results were:

Original length: 226002
trim1: 110ms (length: 225994)
trim2: 79ms (length: 225994)
trim3: 172ms (length: 225994)
trim4: 203ms (length:225994)
trim5: 172ms (length: 225994)
trim6: 312ms (length: 225994)
trim7: 203ms (length: 225994)
trim8: 47ms (length: 225994)
trim9: 453ms (length: 225994)
trim10: 15ms (length: 225994)
trim11: 16ms (length: 225994)
trim12: 31ms (length: 225994)
trim13: 0ms (length: 226002)


Here, this should do all that you need

function doSomething(input) {
    return input
              .replace(/^\s\s*/, '')     // Remove Preceding white space
              .replace(/\s\s*$/, '')     // Remove Trailing white space
              .replace(/([\s]+)/g, '-'); // Replace remaining white space with dashes
}

alert(doSomething("  something with  some       whitespace   "));

Just use string.trim() method. It's supported by all major browsers. Reference here: http://www.w3schools.com/jsref/jsref_trim_string.asp


a recursive try for this

function t(k){ 
    if (k[0]==' ') {
        return t(k.substr(1,k.length));
    } else if (k[k.length-1]==' ') {
        return t(k.substr(0,k.length-1));
    } else {
        return k;
    }
}

call like this:

t("      mehmet       "); //=>"mehmet"

if you want to filter spesific chars you can define a list string basically:

function t(k){
    var l="\r\n\t "; //you can add more chars here.
    if (l.indexOf(k[0])>-1) {
        return t(k.substr(1,k.length));
    } else if (l.indexOf(k[k.length-1])>-1) {
        return t(k.substr(0,k.length-1));
    } else {
        return k;
    }
}

jQuery.trim(" hello, how are you? ");

:)


Here is some methods I've been used in the past to trim strings in js:

String.prototype.ltrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("^[" + chars + "]+", "g"), "" );
}

String.prototype.rtrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("[" + chars + "]+$", "g"), "" );
}
String.prototype.trim = function( chars ) {
    return this.rtrim(chars).ltrim(chars);
}

var word = " testWord ";   //add here word or space and test

var x = $.trim(word);

if(x.length > 0)
    alert('word');
else
    alert('spaces');

This is what is suggested by JavaScript Architect/Guru Douglas Crockford.

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

Note: you have to define "method" for Function.prototype.

Alternatively

String.prototype.trim = function () {
   return this.replace(/^\s+|\s+$/g, '');
};

title.trim();    // returns trimmed title

Observation

In recent browsers, the trim method is included by default. So you don't have to add it explicitly.

Major browsers Chrome, Firefox, Safari etc. supports trim method. Checked in Chrome 55.0.2883.95 (64-bit), Firefox 51.0.1 (64-bit), Safari 10.0 (12602.1.50.0.10).


ECMAScript 5 supports trim and this has been implemented in Firefox.

trim - MDC


If using jQuery is an option:

/**
 * Trim the site input[type=text] fields globally by removing any whitespace from the
 * beginning and end of a string on input .blur()
 */
$('input[type=text]').blur(function(){
    $(this).val($.trim($(this).val()));
});

or simply:

$.trim(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


Here is my current code, the 2nd line works if I comment the 3rd line, but don't work if I leave it how it is.

var page_title = $(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
page_title = page_title.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
page_title = page_title.replace(/([\s]+)/g, '-');