2

What am I doing wrong as both strings below are returning false when tested below?

    var pattern = "^[\s\da-zA-ZåäöÅÄÖ_]+$"
    var reg = new RegExp(pattern);

    console.log(reg.test("This should be invalid as it is full with invalid chars. #!¤%&/()=?"));
    console.log(reg.test("This is an valid string, despite that Swedish chars such as ÅÄÖ are used"));
4

1 に答える 1

7

You need to double-up on the backslashes in the pattern.

var pattern = "^[\\s\\da-zA-ZåäöÅÄÖ_]+$"

The problem is that when you build regular expression objects that way, there are two passes made over the string: one to interpret it as a string, and then a second to interpret it as a regular expression. Both of those micro-syntaxes use \ to mean something, so by doubling them you get a single backslash out of the string constant parse.

If your pattern is really a constant, and not something that you construct dynamically from separate parts, then you can just use the native syntax for regular expressions:

var pattern = /^[\s\da-zA-ZåäöÅÄÖ_]+$/;

Only one backslash is necessary because the pattern is only parsed once, as a regular expression.

于 2012-08-29T15:40:16.893 に答える