Replace all plain-text to class of same div

2019-09-11 09:03发布

问题:

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 ?

回答1:

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>



回答2:

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