Reputation: 88197
if i have a string like
<p>this is some content</p><script>alert('hello');</script>
i want to get the string without any scripts, but with the formatting, how do i do it?
<p>this is some content</p>
i tried
var html = "<p>etc</p><script>alert('hello world');</script>".replace("<script*</script>", "p");
but that gave me something like
".replace("", "p"); $('#blogDescription').html(html); }); });
Upvotes: 0
Views: 222
Reputation: 1035
var html = "<p>etc</p><script>alert('hello world');</script>".replace("<script>").replace("</script>");
Upvotes: 0
Reputation: 50105
You can do this without using regex, by using some DOM manipulation you can run through each of the elements in the DOM fragment created from the string and remove the script
tags.
var html = "<p>etc</p><script>alert('hello world');</script>";
var container = document.createElement('div');
container.innerHTML = html;
function stripScript(parent){
var elements = parent.children;
for(var i = 0; i < elements.length; i++){
if(elements[i].nodeName === 'SCRIPT'){
parent.removeChild(elements[i]);
} else if(elements[i].children.length > 0){
stripScript(elements[i]);
}
}
}
stripScript(container);
console.log(container.innerHTML);
Or with jQuery
var html = "<p>etc</p><script>alert('hello world');</script>";
container = document.createElement('div');
container.innerHTML = html;
$(container).find('script').remove();
console.log(container.innerHTML);
Upvotes: 2