user2078025
user2078025

Reputation: 21

JavaScript, Regex, var in pattern

right now, i have this replace:

var newcontent = newcontent
                .replace(/<div id="container_gallery_"(.*)><\/div>/gi,"");

Is it possible to pass a variable in place of <div id="container_gallery_ ?

My

function delAlbum(a) { }

performs this replace, and I would like to put the variable a into the

-edit-

Thanks for the information provided! Less hairloss!

Upvotes: 2

Views: 205

Answers (3)

Alan Moore
Alan Moore

Reputation: 75222

As the other responders said, you can use a RegExp constructor for that. But while you're at it, you should get rid of that (.*). Assuming it's meant to consume whatever other attributes the <div> has, you'll be better off using [^<>]*. That will confine the match to one element at a time; (.*) is the ultimate escape artist.

But I'm curious: are you really passing in strings like <div id="container_gallery_", including the first part of the HTML element? Or are you only passing a replacement for the attribute's value, (e.g. container_gallery_)? If that's the case, this regex should serve you better:

var regex = new RegExp('<div\s+"` + (your var) + '"[^<>]*></div>', 'gi' );

I'm assuming the `id` attribute is always in the first position which generally not a safe assumption, but it makes the regex a lot easier, both to write and to read. ;)

And don't forget to check the passed-in string for characters that are illegal in an HTML attribute.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707178

To put a variable into the regular expression, you need to construct the regular expression as a string and then pass it to the RegExp object constructor like this:

var target = a + "(.*)></div>";
var newcontent = newcontent.replace(new RegExp(target, "gi"), "");

In general, it is a bad idea to do regex matching on uncontrolled HTML and a really bad idea to do it on HTML that comes from the .innerHTML property because there are lots of legal HTML ways to break your regular expression.

Upvotes: 2

Sirko
Sirko

Reputation: 74036

You can build up the RegExp via the object notation and not the shorthand one:

function delAlbum(a) {
    var regex = new RegExp( a + '"(.*)><\/div>', 'gi' );

    var newcontent = newcontent
                    .replace( regex,"");
    // ...
}

Upvotes: 2

Related Questions