Trim spaces from start and end of string

JavascriptRegex

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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);

Solution 3 - Javascript

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();

Solution 4 - Javascript

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)

Solution 5 - Javascript

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

trim - MDC

Solution 6 - Javascript

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   "));

Solution 7 - Javascript

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);
}

Solution 8 - Javascript

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, '-');

Solution 9 - Javascript

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

Solution 10 - Javascript

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

:)

Solution 11 - Javascript

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

var x = $.trim(word);

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

Solution 12 - Javascript

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()));
  });
});

Solution 13 - Javascript

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).

Solution 14 - Javascript

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;
	}
}

Solution 15 - Javascript

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames JefferyView Question on Stackoverflow
Solution 1 - JavascriptpolygenelubricantsView Answer on Stackoverflow
Solution 2 - JavascriptStoneView Answer on Stackoverflow
Solution 3 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 4 - Javascriptuser590028View Answer on Stackoverflow
Solution 5 - JavascriptChaosPandionView Answer on Stackoverflow
Solution 6 - JavascriptCaffGeekView Answer on Stackoverflow
Solution 7 - JavascriptazatothView Answer on Stackoverflow
Solution 8 - JavascriptJames JefferyView Answer on Stackoverflow
Solution 9 - JavascriptLeoView Answer on Stackoverflow
Solution 10 - JavascriptG-h-o-s-tView Answer on Stackoverflow
Solution 11 - JavascriptJitendraView Answer on Stackoverflow
Solution 12 - JavascriptMark SwardstromView Answer on Stackoverflow
Solution 13 - JavascriptmythicalcoderView Answer on Stackoverflow
Solution 14 - Javascriptmguven guvenView Answer on Stackoverflow
Solution 15 - JavascriptSuperNovaView Answer on Stackoverflow