2

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!

2
  • 3
    It's simple. Just don't use reglar expressions with HMTL and things like this become easy. Commented Feb 16, 2013 at 9:23
  • 1
    Since you are using JS, why don't you access the div by DOM function? (There should be a way with jQuery, I don't know about JS, but there surely has to be some way). Commented Feb 16, 2013 at 9:33

3 Answers 3

2

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,"");
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.