[javascript] Trim string in JavaScript?

How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?

This question is related to javascript string trim

The answer is


The trim from jQuery is convenient if you are already using that framework.

$.trim('  your string   ');

I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)


use simply code

var str = "       Hello World!        ";
alert(str.trim());

Browser support

Feature         Chrome  Firefox Internet Explorer   Opera   Safari  Edge
Basic support   (Yes)   3.5     9                   10.5    5       ?

For old browser add prototype

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

There are a lot of implementations that can be used. The most obvious seems to be something like this:

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

" foo bar ".trim();  // "foo bar"

Flagrant Badassery has 11 different trims with benchmark information:

http://blog.stevenlevithan.com/archives/faster-trim-javascript

Non-surprisingly regexp-based are slower than traditional loop.


Here is my personal one. This code is old! I wrote it for JavaScript1.1 and Netscape 3 and it has been only slightly updated since. (Original used String.charAt)

/**
 *  Trim string. Actually trims all control characters.
 *  Ignores fancy Unicode spaces. Forces to string.
 */
function trim(str) {
    str = str.toString();
    var begin = 0;
    var end = str.length - 1;
    while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
    while (end > begin && str.charCodeAt(end) < 33) { --end; }
    return str.substr(begin, end - begin + 1);
}

Don't know what bugs can hide here, but I use this:

var some_string_with_extra_spaces="   goes here    "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])

Or this, if text contain enters:

console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])

Another try:

console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])

For IE9+ and other browsers

function trim(text) {
    return (text == null) ? '' : ''.trim.call(text);
}

Here it is in TypeScript:

var trim: (input: string) => string = String.prototype.trim
    ? ((input: string) : string => {
        return (input || "").trim();
    })
    : ((input: string) : string => {
        return (input || "").replace(/^\s+|\s+$/g,"");
    })

It will fall back to the regex if the native prototype is not available.


The trim from jQuery is convenient if you are already using that framework.

$.trim('  your string   ');

I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)


I had written this function for trim, when the .trim() function was not available in JS way back in 2008. Some of the older browsers still do not support the .trim() function and i hope this function may help somebody.

TRIM FUNCTION

function trim(str)
{
    var startpatt = /^\s/;
    var endpatt = /\s$/;

    while(str.search(startpatt) == 0)
        str = str.substring(1, str.length);

    while(str.search(endpatt) == str.length-1)
        str = str.substring(0, str.length-1);   

    return str;
}

Explanation: The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.

The function can be called in the following manner as an example.

form.elements[i].value = trim(form.elements[i].value);

Here's a very simple way:

function removeSpaces(string){
return string.split(' ').join('');
}

Simple version here What is a general function for JavaScript trim?

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

The trim from jQuery is convenient if you are already using that framework.

$.trim('  your string   ');

I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)


Here it is in TypeScript:

var trim: (input: string) => string = String.prototype.trim
    ? ((input: string) : string => {
        return (input || "").trim();
    })
    : ((input: string) : string => {
        return (input || "").replace(/^\s+|\s+$/g,"");
    })

It will fall back to the regex if the native prototype is not available.


There are a lot of implementations that can be used. The most obvious seems to be something like this:

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

" foo bar ".trim();  // "foo bar"

I have a lib that uses trim. so solved it by using the following code.

String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };

use simply code

var str = "       Hello World!        ";
alert(str.trim());

Browser support

Feature         Chrome  Firefox Internet Explorer   Opera   Safari  Edge
Basic support   (Yes)   3.5     9                   10.5    5       ?

For old browser add prototype

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

There are a lot of implementations that can be used. The most obvious seems to be something like this:

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

" foo bar ".trim();  // "foo bar"

Here's a very simple way:

function removeSpaces(string){
return string.split(' ').join('');
}

Trim code from angular js project

var trim = (function() {

  // if a reference is a `String`.
  function isString(value){
       return typeof value == 'string';
  } 

  // native trim is way faster: http://jsperf.com/angular-trim-test
  // but IE doesn't have it... :-(
  // TODO: we should move this into IE/ES5 polyfill

  if (!String.prototype.trim) {
    return function(value) {
      return isString(value) ? 
         value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
    };
  }

  return function(value) {
    return isString(value) ? value.trim() : value;
  };

})();

and call it as trim(" hello ")


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

String.prototype.trimLeft = String.prototype.trimLeft || function () {
    return this.replace(/^\s+/, "");
};

String.prototype.trimRight = String.prototype.trimRight || function () {
    return this.replace(/\s+$/, "");
};

String.prototype.trimFull = String.prototype.trimFull || function () {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};

Shamelessly stolen from Matt duereg.


The trim from jQuery is convenient if you are already using that framework.

$.trim('  your string   ');

I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)


Use the Native JavaScript Methods: String.trimLeft(), String.trimRight(), and String.trim().


String.trim() is supported in IE9+ and all other major browsers:

'  Hello  '.trim()  //-> 'Hello'


String.trimLeft() and String.trimRight() are non-standard, but are supported in all major browsers except IE

'  Hello  '.trimLeft()   //-> 'Hello  '
'  Hello  '.trimRight()  //-> '  Hello'


IE support is easy with a polyfill however:

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

You can do it using the plain JavaScript:

function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}

// Let's test it

sentenceOne = "too short";
sentencetwo = "more than the max length";

console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));

I know this question has been asked three years back.Now,String.trim() was added natively in JavaScript.For an instance, you can trim directly as following,

document.getElementById("id").value.trim();

mine uses a single regex to look for cases where trimming is necessary, and uses that regex's results to determine desired substring bounds:

var illmatch= /^(\s*)(?:.*?)(\s*)$/
function strip(me){
    var match= illmatch.exec(me)
    if(match && (match[1].length || match[2].length)){
        me= me.substring(match[1].length, p.length-match[2].length)
    }
    return me
}

the one design decision that went into this was using a substring to perform the final capture. s/\?:// (make the middle term capturing) and and the replacement fragment becomes:

    if(match && (match[1].length || match[3].length)){
        me= match[2]
    }

there's two performance bets I made in these impls:

  1. does the substring implementation copy the original string's data? if so, in the first, when a string needs to be trimmed there is a double traversal, first in the regex (which may, hopefully be partial), and second in the substring extraction. hopefully a substring implementation only references the original string, so operations like substring can be nearly free. cross fingers

  2. how good is the capture in the regex impl? the middle term, the output value, could potentially be very long. i wasn't ready to bank that all regex impls' capturing wouldn't balk at a couple hundred KB input capture, but i also did not test (too many runtimes, sorry!). the second ALWAYS runs a capture; if your engine can do this without taking a hit, perhaps using some of the above string-roping-techniques, for sure USE IT!


Trim code from angular js project

var trim = (function() {

  // if a reference is a `String`.
  function isString(value){
       return typeof value == 'string';
  } 

  // native trim is way faster: http://jsperf.com/angular-trim-test
  // but IE doesn't have it... :-(
  // TODO: we should move this into IE/ES5 polyfill

  if (!String.prototype.trim) {
    return function(value) {
      return isString(value) ? 
         value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
    };
  }

  return function(value) {
    return isString(value) ? value.trim() : value;
  };

})();

and call it as trim(" hello ")


Simple version here What is a general function for JavaScript trim?

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

I had written this function for trim, when the .trim() function was not available in JS way back in 2008. Some of the older browsers still do not support the .trim() function and i hope this function may help somebody.

TRIM FUNCTION

function trim(str)
{
    var startpatt = /^\s/;
    var endpatt = /\s$/;

    while(str.search(startpatt) == 0)
        str = str.substring(1, str.length);

    while(str.search(endpatt) == str.length-1)
        str = str.substring(0, str.length-1);   

    return str;
}

Explanation: The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.

The function can be called in the following manner as an example.

form.elements[i].value = trim(form.elements[i].value);

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

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

Added natively in: JavaScript 1.8.1 / ECMAScript 5

Thus supported in:

Firefox: 3.5+

Safari: 5+

Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

Chrome: 5+

Opera: 10.5+

ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/


Simple version here What is a general function for JavaScript trim?

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

If you are using jQuery, use the jQuery.trim() function. For example:

if( jQuery.trim(StringVariable) == '')

I know this question has been asked three years back.Now,String.trim() was added natively in JavaScript.For an instance, you can trim directly as following,

document.getElementById("id").value.trim();

If you are using jQuery, use the jQuery.trim() function. For example:

if( jQuery.trim(StringVariable) == '')

You can do it using the plain JavaScript:

function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}

// Let's test it

sentenceOne = "too short";
sentencetwo = "more than the max length";

console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));

Flagrant Badassery has 11 different trims with benchmark information:

http://blog.stevenlevithan.com/archives/faster-trim-javascript

Non-surprisingly regexp-based are slower than traditional loop.


Here is my personal one. This code is old! I wrote it for JavaScript1.1 and Netscape 3 and it has been only slightly updated since. (Original used String.charAt)

/**
 *  Trim string. Actually trims all control characters.
 *  Ignores fancy Unicode spaces. Forces to string.
 */
function trim(str) {
    str = str.toString();
    var begin = 0;
    var end = str.length - 1;
    while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
    while (end > begin && str.charCodeAt(end) < 33) { --end; }
    return str.substr(begin, end - begin + 1);
}

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

String.prototype.trimLeft = String.prototype.trimLeft || function () {
    return this.replace(/^\s+/, "");
};

String.prototype.trimRight = String.prototype.trimRight || function () {
    return this.replace(/\s+$/, "");
};

String.prototype.trimFull = String.prototype.trimFull || function () {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};

Shamelessly stolen from Matt duereg.


I have a lib that uses trim. so solved it by using the following code.

String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

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

Added natively in: JavaScript 1.8.1 / ECMAScript 5

Thus supported in:

Firefox: 3.5+

Safari: 5+

Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

Chrome: 5+

Opera: 10.5+

ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/


There are a lot of implementations that can be used. The most obvious seems to be something like this:

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

" foo bar ".trim();  // "foo bar"

For IE9+ and other browsers

function trim(text) {
    return (text == null) ? '' : ''.trim.call(text);
}

mine uses a single regex to look for cases where trimming is necessary, and uses that regex's results to determine desired substring bounds:

var illmatch= /^(\s*)(?:.*?)(\s*)$/
function strip(me){
    var match= illmatch.exec(me)
    if(match && (match[1].length || match[2].length)){
        me= me.substring(match[1].length, p.length-match[2].length)
    }
    return me
}

the one design decision that went into this was using a substring to perform the final capture. s/\?:// (make the middle term capturing) and and the replacement fragment becomes:

    if(match && (match[1].length || match[3].length)){
        me= match[2]
    }

there's two performance bets I made in these impls:

  1. does the substring implementation copy the original string's data? if so, in the first, when a string needs to be trimmed there is a double traversal, first in the regex (which may, hopefully be partial), and second in the substring extraction. hopefully a substring implementation only references the original string, so operations like substring can be nearly free. cross fingers

  2. how good is the capture in the regex impl? the middle term, the output value, could potentially be very long. i wasn't ready to bank that all regex impls' capturing wouldn't balk at a couple hundred KB input capture, but i also did not test (too many runtimes, sorry!). the second ALWAYS runs a capture; if your engine can do this without taking a hit, perhaps using some of the above string-roping-techniques, for sure USE IT!


Use the Native JavaScript Methods: String.trimLeft(), String.trimRight(), and String.trim().


String.trim() is supported in IE9+ and all other major browsers:

'  Hello  '.trim()  //-> 'Hello'


String.trimLeft() and String.trimRight() are non-standard, but are supported in all major browsers except IE

'  Hello  '.trimLeft()   //-> 'Hello  '
'  Hello  '.trimRight()  //-> '  Hello'


IE support is easy with a polyfill however:

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

Don't know what bugs can hide here, but I use this:

var some_string_with_extra_spaces="   goes here    "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])

Or this, if text contain enters:

console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])

Another try:

console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to trim

How to remove whitespace from a string in typescript? Strip / trim all strings of a dataframe Best way to verify string is empty or null Does swift have a trim method on String? Trim specific character from a string Trim whitespace from a String Remove last specific character in a string c# How to delete specific characters from a string in Ruby? How to Remove the last char of String in C#? How to use a TRIM function in SQL Server