Adding a DOT (.) to Regular Expression

2020-04-30 06:26发布

问题:

I'm looking to add a (.) to the allowed characters in my function below:

$(id).bind('keypress', function(event) {
    var regex = new RegExp("[()a-zA-Z0-9 ?,/-]");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

However, every time I add it it comes up with the error:

Uncaught SyntaxError: Invalid regular expression: /[()a-zA-Z0-9 ?,/-.]/: Range out of order in character class

I've tried adding just (.) & also tried adding it with (\.) but still the same error.

Please can you assist to where I need to add this (.) ?

回答1:

Note that - should either be at the beginning or at the end of character class or has to be escaped by a backslash \, since it indicates range as in a-z

/[()a-zA-Z0-9 ?,/.-]/

Also, if dynamic regex is required, just use the regex literal as in above, if not you'd have to remove the delimiters / / and use the actual regex [()a-zA-Z0-9 ?,/.-] as a String which can be used in RegExp constructor.