views:

154

answers:

6

Trying to find a way to trim spaces from the start and end of the string. I was using this, but it dont seem to be working:

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

Any ideas?

A: 

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);
}
azatoth
The RegExp `^[\s*]+` matches `*` at the beginning of the string, so that your function trims `"*** Foo"` to `"Foo"`.
Ferdinand Beyer
probably :) wonder why no one have complained... It was a long time ago I wrote that code, and it's used in http://en.wikipedia.org/wiki/Wikipedia:Twinkle . off source now that you point it out it's obvious.
azatoth
A: 

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

trim - MDC

ChaosPandion
+2  A: 

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   "));
Chad
\s\s* seems redundant, since there is \s+, but it's a little bit faster
Chad
+8  A: 

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

polygenelubricants
@polygenelubricants: great post, great code!
Marco Demajo
The new Safari (5), Chrome(5), Firefox(3.6) and Opera (10.5) all support a native String trim method. That being the case, I'd assign a method to String.prototype, if it does not exist, rather than a new global function.
kennebec
+1  A: 

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, '-');
James Jeffery
remove 2nd
c0mrade
@James Jeffery, so ultimately you're trying to clean this string to be trimmed, alpha-numeric, and dashes instead of spaces as separators?
Chad
@chad yes. To create slug URLs on the fly so users can see what their URL will look like. Similar to how wordpress does it when creating new blog posts.
James Jeffery
+4  A: 

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();
CMS
IE9 had better get compliant...
ChaosPandion