I am looking for a way to replace multiple strings in the same div that has the class name "information". This div appears multiple times on the page and I would like it to work in each instance.
I have managed find a way to achieve with the code below, however this way seems most likely very clunky.
Is there a way to condense this so it doesnt repeat so much and can check by class, then replace each string required?
<script>
var elements = document.getElementsByClassName('information');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var pages = str.replace(" pages", " pp.");
elements[i].innerHTML = pages;
}
var elements = document.getElementsByClassName('information');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var page = str.replace(" page", " p.");
elements[i].innerHTML = page;
}
var elements = document.getElementsByClassName('information');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var colours = str.replace("colour & ", "colour & ");
elements[i].innerHTML = colours;
}
var elements = document.getElementsByClassName('information');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var illustrations = str.replace(" ill", " ill");
elements[i].innerHTML = illustrations;
}
var elements = document.getElementsByClassName('information');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var multiplication = str.replace(" × ", " × ");
elements[i].innerHTML = multiplication;
}
var elements = document.getElementsByClassName('information');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var cm = str.replace(" cm", " cm");
elements[i].innerHTML = cm;
}
var elements = document.getElementsByClassName('information');
for (var i = 0; i < elements.length; i++) {
var str = elements[i].innerHTML;
var langauge = str.replace(" / ", " / ");
elements[i].innerHTML = langauge;
}
</script>
3
Answers
Yes, just repeat
str = str.replace...
for each pattern:Also, you most probably want
replaceAll
, not justreplace
.For my answer, I created an array of the changes, each element having two elements the first being what is replaced and the second is what will replace it.
Then I simply loop through the elements using a forEach and through the array and use each element to replace on innerHTML.
RegExp?
You can use regex to replace specific string patterns, it looks like this: