Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to regex using regexp and test values in javascript

I have a regular expression that is in string form, I want to bind that regex to my grid cell. Such that, now the values in that cell are validated against that regex. I am using RegExp JavaScript library for conversion and testing the value. But it is either returning false everytime or giving me an invalid regex, even for the simplest of the regex used.

This is the method I am using:

addCellValidator(columnObj[0].name, new CellValidator({                 
    isValid: function (value) {
        var regex = new RegExp("/^[a-zA-Z\-]+$/");
        return value == "" || (regex.test(value)); 
    }
}));

Is it the format or any special pattern required by the RegExp?

like image 985
faizanjehangir Avatar asked Apr 13 '26 14:04

faizanjehangir


2 Answers

While this is valid JavaScript code:

new RegExp("/^[a-zA-Z\-]+$/")

... it doesn't generate the regular expression you think. It's equivalent to this:

/\/^[a-zA-Z-]+$\//

You'll have to:

  • Strip delimiters
  • Extract and parse flags, if any, e.g.:

    "/^[a-z-]+$/i" ---> new RegExp("^[a-z-]+$", "i")
    

One more note: there's no point in escaping - with backslash. If want to match a literal - inside a character class you need to put it as first or last item.

like image 124
Álvaro González Avatar answered Apr 16 '26 03:04

Álvaro González


You just added the / / to the string, this works:

addCellValidator(columnObj[0].name, new CellValidator({
                isValid: function (value) {
                    var regex = new RegExp("^[a-zA-Z\-]+$");
                    return value == "" || (regex.test(value)); }
            }));
like image 36
gmaliar Avatar answered Apr 16 '26 04:04

gmaliar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!