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

问题: I am trying to find substring(s) that match an expression ((my substring)) wrap the results with markup and inject different vars on the different results....

问题:

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:

  • 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>

  • 发表于 2019-01-17 19:56
  • 阅读 ( 222 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除