开发者

How to build a regular expression from a variable

开发者 https://www.devze.com 2023-02-14 09:43 出处:网络
I want to build a REGEXP that matches all results that contain a word, that word is in a variable. This is my code:

I want to build a REGEXP that matches all results that contain a word, that word is in a variable. This is my code:

function search(buscar){        
    $(".main h2 a").each(function(index) {
        var rege = /^+buscar+$/; //LINE THAT MUST BE CHANGED***
        if(rege.test($(this).text())){
            alert($(this).text());
        }       
开发者_JS百科    });
}


var rege = new RegExp('^' + buscar + '$');

or

var rege = new RegExp('^' + buscar.replace(/([.?*+^$[\]\\(){}-])/g, '$1') + '$');

if there's any chance of regex metacharacters being passed in buscar, and you don't want them acting as such.

Of course, it's worth noting that, if there are no regex metacharacters in buscar or we escape them, we're constructing a regex that performs exactly the same test as the == operator.

There's nothing jQuery about this line, incidentally; it's vanilla JavaScript.


var rege = /\bbuscar\b/;

Word boundaries

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号