[英]remove div tags and replace some of them by br tag
我有下一段文字:
fffffff<div>hhhhh</div><div>kh</div>
1)我只想刪除div標簽。
2)如果div標簽不在字符串的開頭也不在字符串的末尾,請替換為<br/>
3) </div><div>
應該替換為一個div。
例子:
1) fffffff<div>hhhhh</div><div>kh</div>
-> fffffff<br/>hhhhh<br/>kh
字符串末尾的</div>
標記未替換,因為它位於字符串末尾。
2) <div>fffffff</div><div>hhhhh</div><div>kh</div>
-> fffffff<br/>hhhhh<br/>kh
您可以假設沒有類似以下內容的文字:
<div><div><div><div><div></div><div>text</div><div></div>
查找所有html標簽:
replace(/<[^>]*>/g, "<br/>")
但是它用<br/>
替換了所有的html標簽。
$('.c').html(function(i, v) { return v.replace(/^([\\w\\s]+)(<div>.*?<\\/div>)/, '$1<br/>$2') //-^- For first div .replace(/<div>(.*?)<\\/div>\\s*$/, '$1') //-^- For removing div at ending .replace(/<div>(.*?)<\\/div>/g, '$1<br/>') //-^-For removing other div });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class=c> <div>fffffff</div> <div>hhhhh</div> <div>kh</div> </div> <div class=c> fffffff <div>hhhhh</div> <div>kh</div> </div>
為了符合您的示例:
var str = "fffffff<div>hhhhh</div><div>kh</div>";
if(str.indexOf("<div>") === 0){
str = str.substring(5);
}
if(str.slice(-6) === "</div>"){
str = str.substring(0,str.length - 6);
}
str = str.replace(/<\/div><div>/g,"<br/>");
str = str.replace(/<div>/g,"<br/>");
但要符合您的第三條規則,您應該進行更改
str = str.replace(/<\/div><div>/g,"<br/>");
通過
str = str.replace(/<\/div><div>/g,"<div>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.