javascriptregex

Change Regex to only accept specified characters?


I currently have the regex in a javascript file as:

function (value) {
    regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&|\_|\.]", "i");
    return !regex.test(value);
}

Rather than specifying what characters are not allowed, how can I state what characters are allowed? The characters I want are a-z A-Z 0-9 (and also the actual character "-" but not at the start or end, only inbetween).


Solution

  • regex = new RegExp("^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$");

    Again the classical "normal* (special normal*)*" pattern ;)

    The function body becomes:

    function (value) {
        regex = new RegExp("^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$");
        return regex.test(value) && value.length >= 6;
    }
    

    edit: made grouping non capturing since no capture is done here