最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert string to regex using regexp and test values in javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share edited Jan 17, 2014 at 20:57 Jaak Kütt 2,6564 gold badges33 silver badges40 bronze badges asked Feb 26, 2013 at 12:43 faizanjehangirfaizanjehangir 2,8518 gold badges51 silver badges86 bronze badges 2
  • what values are you testing against? – gmaliar Commented Feb 26, 2013 at 12:46
  • Special characters in this case.. – faizanjehangir Commented Feb 26, 2013 at 12:48
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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)); }
            }));
发布评论

评论列表(0)

  1. 暂无评论