I need to replace characters inside specific tag using javascript when page loads. I have a big list of characters to be replaced. so it will be fast and should work with major brow开发者_运维知识库sers. example:-
<p> The quick brown fox jumps over the lazy dog </p>
will need to looks like
<p> h=f t)ujh lk.,h ghy tfbm' bhjf ghy {>ht Frt </p>
Thanks!
Give <p>
an ID and you're on your way:
<p id='p1'>content...</p>
Javascript:
var text = document.getElementById('p1').innerHTML;
text = text.replace("c","x");
...
document.getElementById('p1').innerHTML = text;
EDIT
To target all <p>
s, do as you said:
var allPs = document.getElementsByTagName("P");
var text;
for(i=0;i<allPs.length;i++) {
text = allPs[i].innerHTML;
text = text.replace("c","x");
allPs[i].innerHTML = text;
}
You may have to run a while
loop over the .replace()
method, since calling it once will only do a single replacement (i.e. only 1 "c" will be replaced).
Use regular expressions and chain multiple replace's together:
window.onload = function() {
var string = document.getElementsByTagName("p")[0].innerHTML;
var replacedString = string.replace(/somespecialchar/gi, "replaceWith").replace(/someotherspecialchar/gi, "replaceWith").replace(/anotherchar/gi, "replaceWith");
document.getElementsByTagName("p")[0].innerHTML = replacedString;
}
精彩评论