Reputation: 196
I am trying to update my html using regex and javascript. I can capture the group I intend, however nothing on the dom is changing the way I would expect.
I want to discover all currency mentions of AUD, I have a regex that is capturing that. I then need to change how it is displayed.
I used the .replace function, however it does not seem to change anything. It only seems to change it in the console.log.
10AUD
Help us all
<p> 20THB</p>
<p> There is 100USD, here</p>
<p>More random sentances that should not be evalued even with 500 numbers in it</p>
<p>Here I can write a bunch like I had 300THB in my pocket and a spare 50AUD note aswell</p>
Here is the js portion.
regAUD = RegExp(/([0-9]+(AUD))/gi);
function checker() {
str = document.getElementsByTagName('p');
//str = str.innerText;
for (i = 0; i < str.length; i++) {
str[i].id = String(i+"para");
console.log(str[i].innerText);
inner = str[i].innerText;
//Now make an if statement to if we go further
//res = isCurrency(inner); //This passes correctly
res = 1;
if(res === 1){
if(regAUD.test(inner)){
inner = inner.replace(regAUD, '<b>$1</b>');
console.log(inner);
console.log("Done?");
}
}
}
}
I assume I am using the function incorrectly. It does show up in the console but not in the elements expected. It doesn't change anything, ie I expect it to currently make 10AUD and 500AUD bold but it does not do this. Is there a better method to achieve this change in the DOM or have I used this function incorrectly?
Upvotes: 1
Views: 257
Reputation: 85
You have to set the paragraph innerHTML porperty after replacing regxmatch to replace in DOM.
regAUD = RegExp(/([0-9]+(AUD))/gi);
function checker() {
str = document.getElementsByTagName('p');
//str = str.innerText;
for (i = 0; i < str.length; i++) {
str[i].id = String(i+"para");
console.log(str[i].innerText);
inner = str[i].innerText;
//Now make an if statement to if we go further
//res = isCurrency(inner); //This passes correctly
res = 1;
if(res === 1){
if(regAUD.test(inner)){
inner = inner.replace(regAUD, '<b>$1</b>');
str[i].innerHTML= inner;
console.log(inner);
console.log("Done?");
}
}
}
}
Upvotes: 0
Reputation: 3623
You forget to affect your new HTML string to the concerned elements' own HTML.
Also, you could have a shorter function.
Here's one with two parameters:
selector
to execute the highlight on wanted elements.currency
to highlight the wanted currency.// Highlights "AUD" mentions winthin all <p> elements.
highlightCurrencyFromElement('p', 'aud');
function highlightCurrencyFromElement(selector, currency) {
const elements = document.querySelectorAll(selector),
pattern = new RegExp(`(\\d+\\s*${currency})`, 'gi');
for (let i = 0; i < elements.length; i++) {
elements[i].innerHTML = elements[i].innerHTML.replace(pattern, '<b>$1</b>');
}
}
<div>
<p>5</p>
<p>21 AUD</p>
</div>
<div>
<p>50AUD</p>
<p>50 €</p>
<p>87 USD</p>
<span>20 AUD (in span, so no highlighted)</span>
<div>
Upvotes: 1