What i need to do is to find a particular strings inside my HTML and if found i will replace it with nothing.
Exp :
HTML:
<img src=`javascript:alert("hello ,world!")`>
What i need to do is to find the occurrence of some keywords like javascript , alert , etc and if found inside HTML tags like the one above i need to replace it with empty string.
i know jquery has some useful functions like
.find() , .replace() and :contains
but really i could not figure out how to do it because i am not that good in javascript.
Help will be appreciated.
It's not clear from your question if you already know what attributes you want to check for, so I will give two solutions- depending whether you know already or not. If you know the attribute where you want to search for the keywords, try this:
var attribVal = $("img").attr("src");
if (attribVal.match(/(javascript)|(alert)/i)
{
$("img").attr("src", "");
}
If you don't know the attribute names, then store the html in a variable and compare in the value of the variable. Assuming the following div to be the parent for the img tag:
<div id="myDiv">
<img src=`javascript:alert("hello ,world!")` id='myImg'>
</div>
Do the following:
var myVar = $("#myDiv").html();
if (attribVal.match(/(javascript)|(alert)/i)
{
$("img#myImg").attr("src", "");
}
What you're doing isn't even something that really needs jQuery to be done easily. Here's an example in pure JavaScript.
HTML
<a id="someLink" src="javascript:alert('hello world!')">LINK THAT DOES STUFF</a>
//how an image tag can have a JS src is beyond me.
Now if I wanted to look for keywords like ' javascript ' in say the src attribute. I would first get the DOM element like so:
var domObject=document.getElementByID('someLink')
/*$('someLink') is jQuery equivalent*/
Now to get what's in said attribute I'd use domObject.getAttribute('src')
this would return "javascript:alert('hello world!')"
Finally I would have a function that brings everything together and simply detects what I'm looking for and empties it.
function getRidofJavascriptInSrc(object){
a=object.getAttribute('src');
if(/javascript/i.test(a)) //this is REGEX, it will look for the keyword JavaScript and run statement if true
{object.setAttribute('src')=""}
}
getRidofJavascriptInSrc($('someLink'));
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.