开发者

Regex replaces everything that matches any character

开发者 https://www.devze.com 2023-01-07 04:28 出处:网络
a[b].innerHTML=a[b].innerHTML.replace(RegExp(\'[\'+bbc[c][0]+\']\',\'ig\'),bbc[c][1]) This is basically what I\'m working with. It\'s wrapped in two loops so that should explain why it looks like wh
a[b].innerHTML=a[b].innerHTML.replace(RegExp('['+bbc[c][0]+']','ig'),bbc[c][1])

This is basically what I'm working with. It's wrapped in two loops so that should explain why it looks like what it does. Basically I want to replace something that matches '['+variable from an array+']'. I'm making a BBCode script for a free forum and no don't point me at any BBCode scripts. The problem is that regex is replacing everything that matches any character. So, it replaces [, q, c, o, d, e, ], all with the second part of the array. (QCODE is an example BBCode being used) I don't know if it does that in a normal /regex/ with [] but it's annoying as hell. I've tried escaping the [] ('\['+v+'\]'), I've tried eval(), I've tried everything you can imagine. I need to make this thing work like it's supposed to, because everything 开发者_如何转开发is set up as it should be. If you know how to fix this, please answer. I'd like you to test your solution before answering though because you have no idea how many methods I've tried to make this work.


Use the right escape character:

RegExp('\\['+bbc[c][0]+'\\]','ig'),

/ is just a regular character (except in regex literals, which you're not using), the escape character is \. You also have to escape twice, once for the string literal, and once for the regex.


The reason why your code is not working is because you are using RegExp, which takes in a string for a regular expression. In this string, you need to escape the backslash escape character. The following will work:

​var str = 'Before. [qcode] After.';
alert(str.replace(RegExp('\\[qcode\\]', 'ig'), 'During.'));​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
0

精彩评论

暂无评论...
验证码 换一张
取 消