简体   繁体   中英

How to replace characters, inside specific tag using javascript

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 browsers. 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 (ie 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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM