Javascript替换不替换

时间:2011-11-16 15:06:53

标签: javascript regex

此代码中的模式不会替换括号。我也试过“/(|)/ g”。

var re = "/[^a-z]/g",
   txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
   // What I expect is strings like "(en)" , "(el)" etc
   txt = txt.replace(re," ")

提前致谢

2 个答案:

答案 0 :(得分:5)

你的正则表达式是一个字符串,这将尝试替换那个确切的字符串。正则表达式对象周围没有引号,只有分隔符。试试这样:

var re = /[^a-z]/g,
   txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
   txt = txt.replace(re," ");

答案 1 :(得分:3)

或者如果您更喜欢字符串(以及更明确的类型):

var re = new RegExp("[^a-z]", "g")