Javascript 将所有纯文本替换为同一div的类
我已经问了相关的问题。Javascript 将所有纯文本替换为同一div的类,javascript,jquery,html,text,replace,Javascript,Jquery,Html,Text,Replace,我已经问了相关的问题。 现在尝试将许多(不止一个)纯文本(如[make this class]替换为类,并将[make-this-class2]替换为同一div上的类问题是js只替换一个文本,这意味着它不会替换同一div的其他文本,当尝试替换多个文本时,它只替换同一div的一个文本。下面给出了示例HTML和js HTML: <div class='not-others-div'> text text [make-this-class] text </div> Text
现在尝试将许多(不止一个)纯文本(如
[make this class]
替换为
类,并将[make-this-class2]
替换为同一div上的
类问题是js只替换一个文本,这意味着它不会替换同一div的其他文本,当尝试替换多个文本时,它只替换同一div的一个文本。下面给出了示例HTML和js 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>
$(".this-div-only").html(function(i, html) {
return html.replace(/\[(.*)\]/, $("<div />", {"class":"$1"})[0].outerHTML)
})
text text[创建此类]text
文本文本文本
text[make this class]text[make-this-class2]和[make-this-class3]以及10个类似的文本
JQuery:
<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>
$(".this-div-only").html(function(i, html) {
return html.replace(/\[(.*)\]/, $("<div />", {"class":"$1"})[0].outerHTML)
})
$(.this div only”).html(函数(i,html){
返回html.replace(/\[(.*)\]/,$(“”,{“类”:“$1”})[0].outerHTML)
})
那么,如何通过jquery将许多文本替换为同一个dom元素div的类(10个十个文本)?在regex中添加
g
全局标志,还需要使用*?
来匹配最短的
$(.this div only”).html(函数(i,html){
返回html.replace(/\[(.*?)\]/g,$(“”{
“类别”:“$1”
})[0]。outerHTML)
})
text[make this class]text[make-this-class2]和[make-this-class3]以及10个类似的文本
text[make this class]text[make-this-class2]和[make-this-class3]以及10 text
尝试添加g(全局),以更改所有眼病:
$(".this-div-only").html(function(i, html) {
return html.replace(/\[(.*)\]/g, $("<div />", {"class":"$1"})[0].outerHTML)
})
$(.this div only”).html(函数(i,html){
返回html.replace(/\[(.*)\]/g,$(“”,{“类”:“$1”})[0].outerHTML)
})
Pranav C Balan以20秒的优势赢了我,谢谢,但只替换了两个文本,无法替换其他8个文本(意味着我试图在同一次跳转中替换10个文本)请修复它。我已经尝试过JSFIDLE,但问题是它不能给我与普通HTML网页相同的结果,意味着它在HTML网页上得到不同的结果。@Aabira:只需添加HTML内容,我们就可以了。您好,谢谢,但它只替换了两个,无法替换其他8个文本(意味着我试图在同一次尝试中替换10个文本),请修复它。