1

I need to adjust a string like so:

Cases where things should be adjusted:

Case a: "        ", becomes ""
Case b: "z       ", becomes "z"
Case c: "        z", becomes "z"

Cases where things shouldn't be adjusted:

Case d: " z ", stays the same

Case e: "zzz zz          zzz", stays the same

How can I achieve this in javascript?

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
williamsandonz
  • 15,864
  • 23
  • 100
  • 186

4 Answers4

3

You can use String.trim() for this case. It removes the leading and trailing whitespace from a string. Many modern browsers support this method, which allows you to rewrite the above much shorter.

mystring = mystring.trim()

For browsers that do not support String.trim(), create your own method using a regular expression.

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

Alternatively, for most cases using it directly will perform the same.

mystring.replace(/^\s+|\s+$/g, '')

See live demo

hwnd
  • 69,796
  • 4
  • 95
  • 132
3

You should use the ES5 .trim() method:

"        ".trim(); // "";
"z       ".trim(); // "z";
"       z".trim(); // "z";
"   z    ".trim(); // "z";
"zzz zz          zzz".trim(); // "zzz zz          zzz";

For compatibility with old browsers, you can add the following at the beginning of your script:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
3

Inspired by Xander, try this, match all but variable e:

return s.replace(/^(\s+$|\w{1}\s+$|\s+\w{1}$|\s+\w{1}\s+$)/i, "Bingo");

And here is the Demo, hope this can help you :P

Community
  • 1
  • 1
Santino_Wu
  • 53
  • 6
1

Its enough for you to use trim function; but string.trim(); wont work in all browsers...

Try this:

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

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

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

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

Since new Browsers (IE9+) have trim() already implemented, you should only implement trim() if it is not already available on the Prototype-Object (overriding it is a huge performance hit). This is generally recommended when extending Native Objects! Note that the added property is enumerable unless you use ES5 Object.defineProperty!

if (!String.prototype.trim) {
   //code for trim
}
Legionar
  • 7,472
  • 2
  • 41
  • 70
  • 1
    You could have said your answer is a perfect duplicate of [Pradeep Kumar Mishra](http://stackoverflow.com/users/22710/pradeep-kumar-mishra)'s [one](http://stackoverflow.com/a/498995/1529630). – Oriol Nov 15 '13 at 00:54
  • 1
    Yes, its perfect, plus another sentense at the beginning. – Legionar Nov 15 '13 at 00:57