0

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?

Paul Ness
  • 113
  • 1
  • 7

2 Answers2

2

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);
Reid Horton
  • 526
  • 2
  • 7
  • Oops...my bad. What happens if I want to pass in a variable though, that's why I was using it as a string? – Paul Ness Aug 26 '16 at 20:37
  • 1
    You should use this too then, http://stackoverflow.com/a/3561711/772035, and use `Regex.escape( name )` instead of just `name` directly, in case `name` contains characters that get interpreted with special meaning in regex, such as if name contains a `.`. – Paul Aug 26 '16 at 20:48
0

You are using String to replace. Try fileData.replace(new RegExp(findInDom, 'g'),"")

user1211
  • 1,507
  • 1
  • 18
  • 27