changing color all occurrences of specific signs in the given sentence

Viewed 38

I want to color all / and + signs in the given text so I tried this:

const grammarStructure = document.querySelector(".grammar-structure");

grammarStructure.innerHTML = getColoredStructure("have / has + been + ing");

function getColoredStructure(text) {
   let result = text;
   result = result.replaceAll('+', "<span class='action'>+</span>");
   result = result.replaceAll('/', "<span class='action'>/</span>");
   return result;
}
.action {
  color: #ff0033;
}
<div class="grammar-structure"></div>

But as you see it doesn't work correctly! I guess the / sign in each span is replaced too and that causes the issue...

How can I fix this?

2 Answers

As @pilchard mentioned in the comments above, you can use regExp

const grammarStructure = document.querySelector(".grammar-structure");

grammarStructure.innerHTML = getColoredStructure("have / has + been + ing");

function getColoredStructure(text) {
  let result = text;
  result = result.replace(/([\/])/g, "<span class='action'>$1</span>");
  result = result.replace(/([\+])/g, "<span class='action-2'>$1</span>");
  return result;
}
.action {
  color: #ff0033;
}

.action-2 {
  color: yellow;
}
<div class="grammar-structure"></div>

The forward slash is treated as an escape character.

To get round all the mess with single and double quotes and forward slash you can use backtick character to delimit your strings. This makes the code a lot easier to read and saves the difficulty of creating regex statements.

See this snippet (however, the + was still being interpreted as an operator so I cheated and switched the two replaceAll statements round - will investigate).

const grammarStructure = document.querySelector(".grammar-structure");

grammarStructure.innerHTML = getColoredStructure("have / has + been + ing");

function getColoredStructure(text) {
   let result = text;
   result = result.replaceAll(`/`, `<span class='action'>/</span>`);
   result = result.replaceAll(`+`,`<span class='action'>+</span>`);
   return result;
}
.action {
  color: #ff0033;
}
<div class="grammar-structure"></div>

Related