I have a working reg expression that does a replace function based on the expression. It works perfect. It finds a specific string ba开发者_JS百科sed on the beginning of the string and the expression. This is it:
str.replace(/\bevent[0-9]*\=/, "event");
what this does is it changes event=1
to event
.
What if event
was a variable word? What if I needed to look for conference
also?
I have tried:
var type = "conference";
str.replace(/\b/ + type+ /[0-9]*\=/, "conference");
and:
str.replace(/\b/type/[0-9]*\=/, "conference");
neither worked.
how can I pass a javascript string into a regular expression?
Instead of writing a RegEx literal, use a string to create a new RegExp object:
str.replace(new RegExp('\b' + var + '[0-9]'), …)
You can do that with the RegExp
Object:
str.replace(RegExp('\b' + reStr + '[0-9]*\='),StrToReplaceWith)
Create a new regex object with your variable.
read this...
http://www.w3schools.com/js/js_obj_regexp.asp
精彩评论