javascriptregexstringmatch

Javascript: Use regex to check if a string has values only from another one?


I have a characters string which contains the allowed chars. I would like to check another string (input) if it has values only from the characters.

I don't no if it's possible but looking for a solution which uses regex and match() to determine if the input has only allowed characters.


Solution

  • JS fiddle

    Give this a go. Success will be true when the test string contains only the allowed characters. This is case sensitive.

    var allowedCharacters = "abcdefghijklmnopqrstuvwxyz";
    var regex = new RegExp("^[" + allowedCharacters + "]*$");
    var testString = "abc#@#";
    var success = regex.test(testString);
    

    For case in-sensitive replace the respective line with the below. This adds a regex modifier.

    var regex = new RegExp("^[" + allowedCharacters + "]*$", "i");
    

    If you have special characters in your allowedCharacters variable you must escape them with a double slash. So to allow the square bracket character as well you must use.

    var allowedCharacters = "abc\\[";
    

    This is because the first backslash is for the string escape and the second is to make it an escape in the regex.