Javascript replace using regexp

2020-05-01 06:28发布

<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.

2条回答
聊天终结者
2楼-- · 2020-05-01 06:44

If you construct a RegExp from the new RegExp(...) syntax, then you need two backslashes to escape a character.

new RegExp("^\\[" + nivel[i] + "\\]\\[.+\\].+", "g");
查看更多
Bombasti
3楼-- · 2020-05-01 06:59
  1. 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 \[.
  2. Keep in mind that the regexp \[.+\] matches strings like [abc][def]. You probably want \[\w+\] or something similar.
查看更多
登录 后发表回答