3

How do I test for no whitespaces in a string, using regex? I'm using JQuery

var postcode = $(this), val = postcode.val();

if(val.test(NO WHITESPACE)){
   ...
}

Any help is appreciated, Thanks

1
  • 1
    If you were just looking for space characters, it would have saved some time and confusion if you had been more specific in the question. Commented Apr 7, 2011 at 15:55

5 Answers 5

4
if (/\s/.test(string)) alert("OH NO THERE IS FILTHY WHITESPACE IN THAT STRING");

The "\s" ... uhh, thing, in a regex means "any whitespace character". Specifically, it means the same as this:

[ \f\n\r\t\v\u00A0\u2028\u2029]

which is to say, space, form feed, line feed, carriage return, tab, vertical tab, and some space-like characters from extended Latin and Unicode.

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

Comments

1

If it's only spaces, you don't need a RegExp: no spaces = val.indexOf(' ') < 0

2 Comments

What about other forms of Whitespace like Tab characters, newlines, ...?
In that case a regular expression is the better tool: no whitespace in string => val.match(/\s/g) === null
1

Just use:

if(!val.match(/\s/)) {
  ...
}

Comments

0

Use the following code this would replace all the blank spaces..

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

In fact it would remove even newline characters

The spaces are actually removed by \s

1 Comment

This will not remove all the white spaces but only those at the begining and at the end of the string. And more, this doesn't answer the question.
0
var valid = !/\s/.test('IHaveNoWhiteSpace')

valid ; //# => true

var valid = !/\s/.test('I Have WhiteSpace')

valid ; //# => false

var isValidPostCode = /^[a-z]{2}\d{3}[a-z]{2}$/i.test('TN809EX');

isValidPostCode ; //# => false

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.