1

I want to change the color of keywords of given sentence. So far I have this:

const engSample = document.querySelector(".eng-sample"); engSample.innerHTML = getColoredEngSample("I have been walking"); function getColoredEngSample(text) { let result; const keywords = ["have", "has", "been", "ing"]; keywords.forEach(key => { result = text.replace(key, `<span class='bold-sample'>${key}</span>`); }); return result; }
.bold-sample { color: #ff3c00; }
<p class="eng-sample"></p>

As you see only ing color changes and the rest of keywords not.

How can I fix this or achieve the same result using regex?

2 Answers 2

2

You're replacing result with original text on every iteration. So you should change your code to be:

function getColoredEngSample(text) { let result = text; const keywords = ["have", "has", "been", "ing"]; keywords.forEach(key => { result = result.replace(key, `<span class='bold-sample'>${key}</span>`); }); return result; } 
Sign up to request clarification or add additional context in comments.

Comments

2

The problem is that you use your variable text which doesnt change over time. Every time your loop starts a round it will use the same text from your parameter text. On the next run of the loop the text-change is written to result but never used again. So result will only contain the result of the last loop pass.

const engSample = document.querySelector(".eng-sample"); engSample.innerHTML = getColoredEngSample("I have been walking"); function getColoredEngSample(text) { let result = text; const keywords = ["have", "has", "been", "ing"]; keywords.forEach(key => { result = result.replace(key, `<span class='bold-sample'>${key}</span>`); }); return result; }
.bold-sample { color: #ff3c00; }
<p class="eng-sample"></p>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.