Replace all plain-text to class of same div

2019-09-11 08:27发布

I have asked related question here.
Now trying to replace many (more then one) plain-text like [make-this-class] to class like <div class='make-this-class'></div> and [make-this-class2] to a class like <div class='make-this-class2'></div> on same div <div class='this-div-only'></div>.

Problem is given js replace only one single text, means its not replace others text of same div, when trying to replace text more then one it replace only one text of same div. Example HTML and JS given below.

HTML:

<div class='not-others-div'>
text text [make-this-class] text
</div>

Text text text

<div class='this-div-only'> <!-- this div only -->
text [make-this-class] text [make-this-class2] and [make-this-class3] and 10 text like this <!--trying to replace text more then one-->
</div>

JQuery:

$(".this-div-only").html(function(i, html) {
  return html.replace(/\[(.*)\]/, $("<div />", {"class":"$1"})[0].outerHTML)
})

So how to replace many text to a class (10 ten text) of same div of dom elements by jquery ?

2条回答
Luminary・发光体
2楼-- · 2019-09-11 08:46

Try adding g (global), to change all ocurrences:

$(".this-div-only").html(function(i, html) {
  return html.replace(/\[(.*)\]/g, $("<div />", {"class":"$1"})[0].outerHTML)
})

Pranav C Balan won me by 20 seconds

查看更多
不美不萌又怎样
3楼-- · 2019-09-11 08:53

Add g global flag in regex, and also you need to use .*? for matching the shortest

$(".this-div-only").html(function(i, html) {
  return html.replace(/\[(.*?)\]/g, $("<div />", {
    "class": "$1"
  })[0].outerHTML)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='this-div-only'>
  <div class='this-div-only'>
    <!-- this div only -->
    text [make-this-class] text [make-this-class2] and [make-this-class3] and 10 text like this
    <!--trying to replace text more then one-->
    text [make-this-class] text [make-this-class2] and [make-this-class3] and 10 text
  </div>

查看更多
登录 后发表回答