Paul Ness Paul Ness - 3 months ago 10
Javascript Question

Special character causing issues with JS replacement

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?

Answer

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 wan 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);