0

I making some server reguests and the server reply me with a string that has a lot of spaces in front of the string. the string is USERNAME EXIST

I know how to use this:

String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');};

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

but the first the first answer me USERNAMEEXISTS and the second on " USERNAME EXIST"(with one space in front of the string). Is there any way to kill all white spaces before and after the string?

BlackM
  • 3,927
  • 8
  • 39
  • 69

2 Answers2

1

Use ^ to match the start of a string and $ to match the end of it in a regular expression:

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

Normally stripping whitespace is called trimming and is already implemented natively in modern browsers. So you may want to use this:

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

Which will create a shim for trim if it doesn't already exist, otherwise it will leave the native implementation (which is much faster) in place.

Paul
  • 139,544
  • 27
  • 275
  • 264
0

String trimming is an interesting subject. Some browsers can optimize certain regular expressions better than others. Here's a good article: http://blog.stevenlevithan.com/archives/faster-trim-javascript

I normally use the first method from that article:

String.prototype.killWhiteSpace = function() {
  return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};

Note that this article (and this solution) focuses on performance. That may or may not be important to you, and other answers here will certainly fit the bill.

Zach Shipley
  • 1,092
  • 6
  • 5