JavaScript的使用替换正则表达式 [英] Javascript replace using regexp
本文介绍了JavaScript的使用替换正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<输入类型=文本值=[tabelas] [东西] [美洲]ID =allInput>
<脚本类型=文/ JavaScript的>allInput =的document.getElementById('allInput');VAR NIVEL =新的Array('tabelas','produto');
对于(VAR I = 0; I< nivel.length;我++)
{
警报(OI =>中+ allInput.value +< - + NIVEL [I]);
变种重新=新正则表达式(^ \\ [+ NIVEL [I] +\\] \\ + + \\]。,G);
警报(重新);
allInput.value = allInput.value.replace(
再次,OLA);
警报(OI 2 =>中+ allInput.value +< - + NIVEL [I]);
}
< / SCRIPT>
基本上我whant取代something2在[tabelas] [东西] [otherfield]由若干数量的,我一直在玩的正则表达式,不得不从这个使用.replace(不同的结果/ EX pression / ,XXX)和新的RegExp()。
最好的问候,并感谢您的任何帮助。
解决方案
- 您需要再次逃脱这样的逃逸被正则表达式的构造,不是JavaScript的解析器看到。
\\ [
将导致字符串<$ C $在C> [,\\\\ [
将导致\\ [
。 - 请记住,正则表达式
\\ [+ \\]
匹配字符串如[ABC] [高清]
。您可能希望\\ [\\ w + \\]
或类似的东西。
<input type="text" value="[tabelas][something][oas]" id="allInput">
<script type="text/javascript">
allInput = document.getElementById('allInput');
var nivel = new Array('tabelas', 'produto');
for (var i =0; i < nivel.length ; i++ )
{
alert(" oi => " + allInput.value + " <-- " + nivel[i]) ;
var re = new RegExp("^\[" + nivel[i] + "\]\[.+\].+", "g");
alert(re);
allInput.value = allInput.value.replace(
re, "OLA");
alert(" oi 2 => " + allInput.value + " <-- " + nivel[i]) ;
}
</script>
Basically I whant to replace "something2 in the [tabelas][something][otherfield] by a number of quantity, I have been playing with regexp and had different results from this using .replace(/expression/,xxx ) and new RegExp() .
Best regards and thank you for any help.
解决方案
- You need to double-escape so the escape is seen by the regexp constructor, not the Javascript parser.
"\["
will result in the string[
,"\\["
will result in\[
. - Keep in mind that the regexp
\[.+\]
matches strings like[abc][def]
. You probably want\[\w+\]
or something similar.
这篇关于JavaScript的使用替换正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文