views:

382

answers:

5

Hi!

I try to write a simple Markdown parser in JavaScript. Therefore I want to check for the [link content][link id] syntax. I use the following code:

data = data.replace( /\[(.*?)\][ ]*\[([0-9]+)\]/g, '<a href="$2">$1</a>' );

It works well, but now I want to do this with a RegExp object. So I set up the following bit of code:

var r = new RegExp( '\[(.*?)\][ ]*\[([0-9]+)\]', 'g' );
data = data.replace( r, '<a href="$2">$1</a>' );

But it doesn't work. It even says that my regular expression (which works since the first example does a good job) is invalid:

unmatched ) in regular expression

I think it must have to do with some RegExp-object peculiarities I am not aware of. What am I doing wrong and how can the problem be solved?

+5  A: 

Because the first argument of the RegExp object is a string, not a pattern literal, you have to escape the backslashes, since you want literal backslashes in the pattern:

var r = new RegExp( '\\[(.*?)\\][ ]*\\[([0-9]+)\\]', 'g' );
Sean Bright
Uhm.. didn't think about those string issues. Now it's obvious. Thanks :-)
okoman
@BaileyP: thanks for the edit!
Sean Bright
A: 
var r = /\[(.*?)\][ ]*\[([0-9]+)\]/g;
data = data.replace( r, '<a href="$2">$1</a>' );
chills42
A: 

Double escape you backslashes:

var r = new RegExp( '\\[(.*?)\\][ ]*\[([0-9]+)\\]', 'g' );
Quassnoi
A: 

You need to double escape:

var r = new RegExp( '\\[(.*?)\\][ ]*\\[([0-9]+)\\]', 'g' )
meouw
+1  A: 

In addition to the pattern's backslash problem, this:

data = data.replace( r, '<a href="$2">$1</a>' );

could be dangerous. I'll assume you've already taken care of the HTML-escaping, so I won't be able to do this:

[<script>stealCookies()</script>][http://oops.example.com/]
[hover me][http://hello" onmouseover="stealCookies()]

but you'll still need to check the URL is a known-good scheme so I can't do this:

[click me][javascript:stealCookies()]

You'll probably want to use the String.replace(r, func) variant of the method, and include validation in your replacement-making 'func'.

bobince