Regex to check if whitespace present?

2020-07-03 10:30发布

Seems pretty simple, but cannot figure out why this javascript code isn't working returning false, when expecting true) - I'm guessing it has got to do something with the escape characters? Could someone please help me write a JS block that will return true if whitespace present?

var inValid = new RegExp("[\s]");
var value = "test space";
var k = inValid.test(value);
alert(k);

4条回答
够拽才男人
2楼-- · 2020-07-03 10:33

You don't need the brackets, you would need to escape the backslash (if using the string form) and the built-in regex syntax is easier because you don't have to escape backslashes when using the built-in regex syntax.

var inValid = /\s/;
var value = "test space";
var k = inValid.test(value);
alert(k);

查看更多
来,给爷笑一个
3楼-- · 2020-07-03 10:38

If you want to match something there, but no whitespace:

alert(/^\S+$/.test(value));
查看更多
▲ chillily
4楼-- · 2020-07-03 10:39

You need a double escape character:

one for the "s" and one for the "\" itself:

var inValid = new RegExp("[\\s]");
查看更多
闹够了就滚
5楼-- · 2020-07-03 10:55

You need to escape the backslash if you are creating your RegExp object from a string literal:

var inValid = new RegExp("[\\s]");

Alternatively you can just use the following:

var inValid = /\s/;

This uses a regular expression literal so the escaping of the backslash is not necessary, and there is no need for the character class here so I dropped the square brackets as well.

查看更多
登录 后发表回答