JavaScript RegExp Objects

I am trying to write a simple Markdown parser in JavaScript. So I want to check the syntax [link content][link id]. I am using the following code:

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

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

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

But that will not work. He even says that my regex (which works from the first example does a good job) is invalid:

unmatched) in regular expression

I think this should be due to some features of RegExp objects that I don't know about. What am I doing wrong and how can I solve the problem?

+3
source share
5 answers

RegExp , , , :

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

:

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

. , HTML, :

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

, URL- , :

[click me][javascript:stealCookies()]

, String.replace(r, func) "func" .

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

:

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

escape:

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

Source: https://habr.com/ru/post/1702768/


All Articles