Reputation: 485
I want to sanitize html tags from my wysiwyg. I want to replace certain tags with another. This almost works only the replaceWith() is also removing the content from within the tags. I dont want to do this. I just want to replace the tags. Here is what I have so far.
Text for Testing:
This<div>is</div><div>a test</div><div>to clean </div><div>some tags</div><div><br></div>
Expected Result:
This<p>is</p><p>a test</p><p>to clean</p><p>some tags</p><p><br></p>
Actual Result:
This<p></p><p></p><p></p><p></p><p></p>
This is the code I am using to find and replace
var thebad = ["h1","h2","h3","h4","h5","h6","div"];
var thegood = ["","","","","","","<p>"];
for(var i = 0; i < thebad.length; i++){
$('.content').contents().find('body').find(thebad[i]).replaceWith(thegood[i]);
}
I need to figure out how to keep the text inside the html tags when i replace them.
Thanks in advance
Upvotes: 0
Views: 565
Reputation: 339
Try this:
var text = $("#test").html();
var replace_tags = { "<div>": "<p>", "</div>": "</p>", "<div ": "<p "}; //edited
$.each( replace_tags, function(i,v){
text = text.replace(new RegExp(i, 'g'),v);
});
//console.log(text);
Tested on:
<div id='test'>
<h1>dummy text</h1>
<div>dummy text</div>
<h1>dummy text</h1>
<p>dummy text</p>
<div>dummy text</div>
</div>
Results:
<h1>sadsad</h1>
<p>sadsad</p>
<h1>fsdfsd</h1>
<p>dasdasdasdsad</p>
<p>sadsad</p>
Upvotes: 0
Reputation: 2233
$("div").replaceWith(function() {
var $div = $(this);
return $("<p />")
//.attr('class', $div.attr('class')) // uncomment if you need to give back same class value
.html($div.html());
});
Upvotes: 0
Reputation: 14827
Try this:
$('div').contents().unwrap().wrap('<p />');
EDIT:
$('div').replaceWith(function(){
return $("<p />").append($(this).contents());
});
Upvotes: 1