Adding a DOT (.) to Regular Expression

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 (.) ?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply