Javascript 使用正则表达式替换
<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>
基本上我想用一定数量替换 [tabelas][something][otherfield] 中的“something2”,我一直在使用 regexp,并使用 .replace(/expression/,xxx ) 和 new RegExp(致以
诚挚的问候并感谢您的帮助。
<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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
"\["
将生成字符串[
," \\["
将产生\[
。\[.+\]
与[abc][def]
等字符串匹配。您可能需要\[\w+\]
或类似的东西。"\["
will result in the string[
,"\\["
will result in\[
.\[.+\]
matches strings like[abc][def]
. You probably want\[\w+\]
or something similar.如果您使用
new RegExp(...)
语法构造 RegExp,则需要两个 反斜杠来转义字符。If you construct a RegExp from the
new RegExp(...)
syntax, then you need two backslashes to escape a character.