I have the next text:
fffffff<div>hhhhh</div><div>kh</div>
1) I want to remove only div tags.
2) If the div tag is not in the first of the string and not in the end of the string, replace it by <br/>
3) </div><div>
should be replaced by one div.
examples:
1) fffffff<div>hhhhh</div><div>kh</div>
-> fffffff<br/>hhhhh<br/>kh
The </div>
tag at the end of the string was not replaced cause it's at the end of the string.
2) <div>fffffff</div><div>hhhhh</div><div>kh</div>
-> fffffff<br/>hhhhh<br/>kh
You can assume that there is no text something like:
<div><div><div><div><div></div><div>text</div><div></div>
Find all html tags:
replace(/<[^>]*>/g, "<br/>")
But it replaces all the html tags by <br/>
You can use html()
and replace()
for that
$('.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>
To match your examples :
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/>");
but to match your third rule you should to change
str = str.replace(/<\/div><div>/g,"<br/>");
by
str = str.replace(/<\/div><div>/g,"<div>");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.