jquery: how to use regex to wrap a substring with html some markup and insert variable?

Viewed 37

I am trying to

  1. find substring(s) that match an expression ((my substring))
  2. wrap the results with markup and
  3. inject different vars on the different results.

It works for one substring:

var link1 = "URL_1",
    myRegex = /(\(\(.*\)\))/g,
    myOldString = "lorem ((ipsum dolor)) sit amet consectur";

var myNewString = myOldString.replace(myRegex, "<a href='"+link1+"' class='red'>$1</a>");
$('.mytext').html(myNewString);
.red {
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 class="mytext"></h2>

But I can't get it to work with multiple results:

var link1 = "URL_1",
    link2 = "URL_2",
    myRegex = /(\(\(.*\)\))/g,
    myOldString = "lorem ((ipsum dolor)) sit ((amet)) consectur";

var myNewString = myOldString.replace(myRegex, "<a href='"+link1+"' class='red'>$1</a>", "<a href='"+link2+"' class='red'>$2</a>");


$('.mytext').html(myNewString);

Any hint?

1 Answers
  • Your comma between the output strings breaks the replace
  • The match does not return $1 and $2 but $1 twice - if you want all at once, use .exec and a while loop, but I recommend instead use a function
  • You also need to make the RegEx lazy with a ? or it will match from (( to the end of the second ))

var urls=["URL1","URL2"],cnt=0;
  myRegex = /(\(\(.*?\)\))/g,
  myOldString = "lorem ((ipsum dolor)) sit ((amet)) consectur";

var myNewString = myOldString.replace(myRegex, 
  function(str) { return "<a href='" + urls[cnt++] + "' class='red'>"+str+"</a>" });


$('.mytext').html(myNewString);
.red {
  color: red; text-decoration:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 class="mytext"></h2>

Related