Regex to check if whitespace present?

后端 未结 5 1775
失恋的感觉
失恋的感觉 2021-02-13 01:21

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 esca

相关标签:
5条回答
  • 2021-02-13 01:42

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

    0 讨论(0)
  • 2021-02-13 01:43

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

    alert(/^\S+$/.test(value));
    
    0 讨论(0)
  • 2021-02-13 01:49

    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.

    0 讨论(0)
  • 2021-02-13 01:50

    You need a double escape character:

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

    var inValid = new RegExp("[\\s]");
    
    0 讨论(0)
  • 2021-02-13 01:58

    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);

    0 讨论(0)
提交回复
热议问题