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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.