0

Hey all I am trying to have a simple way of adding multiple item names to a regex list:

var whatToLookFor = "DOZ,DOB".split(",");
var highlightThis = "";

$.each(whatToLookFor,function(i){
   highlightThis += whatToLookFor[i] + "\/|";
});

highlightThis = "\/" + highlightThis.replace(/.$/,"\/gi");

console.log(highlightThis);

/DOZ\/|DOB\//gi <-highlightThis should look like this

$('.string-example').highlightWithinTextarea({
    highlight: highlightThis
});

However, I am not getting the same values shown on the page using highlightThis as I do when using the /DOZ/|DOB//gi. I output the value of highlightThis and it looks just like it should but still does not work for some reason.

$('.string-example').highlightWithinTextarea({
    highlight: /DOZ\/|DOB\//gi
});

What could I be missing in order for it to treat it like a regex value? It's probably something simple that I am just overlooking. :o)

The code I am using is here

final working code

var whatToLookFor = "DOZ,DOB".split(",");
var highlightThis = "";

$.each(whatToLookFor,function(i){
    highlightThis += whatToLookFor[i] + "/|";
});

highlightThis = highlightThis.replace(/.$/,"");

$('.string-example').highlightWithinTextarea({
    highlight: new RegExp(highlightThis, 'gi')
});
StealthRT
  • 10,108
  • 40
  • 183
  • 342

1 Answers1

1

The difference is you're creating it as a string vs as a regex. Instead of adding on gi at the end, use new RegExp and pass your string in and then your flags:

new RegExp('DOZ\\/|DOB/', 'gi');

This will output what you're expecting:

/DOZ\/|DOB//gi
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90