Skip to content

Instantly share code, notes, and snippets.

@JoshyFrancis
Last active May 22, 2018 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshyFrancis/1a7fff99e7878cff611ba185fc72ca83 to your computer and use it in GitHub Desktop.
Save JoshyFrancis/1a7fff99e7878cff611ba185fc72ca83 to your computer and use it in GitHub Desktop.
JavaScript function to replace/highlight any content within html
var replace_within_tags=function(str,find,replace){//replace_within_tags('<a href="javascript:;"> an example <span> another <b>exa</b>mple</span> </a>','exa','EXA');
str=str+'';
find=(find+'').toLowerCase();
replace=replace+'';
var c='',tag_open=false,out='',temp='';
for(var i=0;i<str.length;i++){
c=str.substr(i,1);
switch(c){
case '<':
out+=temp;
temp='';
tag_open=true;
out+=c;
break;
case '>':
out+=temp;
temp='';
tag_open=false;
out+=c;
break;
default:
if(tag_open==false){
temp+=c;
if( find.substr(0,temp.length)==temp.toLowerCase()){
if(find.length==temp.length){
out+=replace;
temp='';
}
}else {
out+=temp;
temp='';
}
}else{
out+= c;
}
break;
}
}
return out+temp;
};
replace_within_tags('<a href="javascript:;"> an example <span> another <b>exa</b>mple</span> </a>','exa','EXA');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment