Reputation: 113
I have this code:
var fileData = '<div name="test1"><h1>Test Div 1</h1></div><!-- Start: FindMe --><div name="findme"></div><!-- End: FindMe -->';
var findInDom = "<!-- Start: FindMe -->.*?<!-- End: FindMe -->";
var result = fileData.replace(findInDom, "");
console.log(result);
I'm trying to find everything from and including:
<!-- Start: FindMe -->
and
<!-- End: FindMe -->
But this code below is not replacing eveything from <!-- Start: FindMe -->
to <!-- End: FindMe -->
so I'm guessing it's a special character issue with -->
causing issues maybe?
My HTML:
<div name="test1"><h1>Test Div 1</h1></div><!-- Start: FindMe --><div name="findme"></div><!-- End: FindMe -->
My Regex/replace:
var findInDom = "<!-- Start: FindMe -->.*?<!-- End: FindMe -->";
My Regex with variable:
var findInDom = /<!-- Start: " + name + " -->.*?<!-- End: " + name + " -->/;
--- name being a variable.
Any ideas why this is not replacing?
Upvotes: 0
Views: 49
Reputation: 536
findInDom
is a string, but you're treating it like a regular expression.
Instead, you want to use a regular expression like so:
var findInDom = /<!-- Start: FindMe -->.*?<!-- End: FindMe -->/;
If you want to insert the values of variables into your regex, use the regex constructor instead:
var name = "FindMe";
var findInDom = "<!-- Start: " + name + " -->.*?<!-- End: " + name + " -->";
var regex = new RegExp(findInDom);
var result = fileData.replace(regex);
Upvotes: 2
Reputation: 1515
You are using String to replace. Try fileData.replace(new RegExp(findInDom, 'g'),"")
Upvotes: 0