views:

47

answers:

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

+3  A: 

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.

Matthew Flaschen
The post was a typo because I was rushing. I used the right escape character, it didn't work. That's why I said test before answering.
Ruffian
Well, fix the question then.
Dolph
If you haven't seen I have, a minute before your response.
Ruffian
@Ruffian, you actually need to use `'\\\['` , because you're escaping once for the string literal, and once for the regex. I left that out before.
Matthew Flaschen
+1 on the update. I had missed that in my answer too.
patrick dw
I didn't see your updated answer before I posted mine. Good job. The lesson learned from all this is that problem typos distract from the real issue. I've seen this error made very often, but because I was confused from the question, didn't catch it right away.
TNi
+1  A: 

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.'));​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
TNi
That does work. It seems like something I should've thought of. If only I could rate your answer high more than once, thanks man.
Ruffian