-2

I am trying to color a specific part of a string, this is what I have so far:

    function SpecialColor(num) {
   const color = document.getElementById(`alignColor${num}`).value;
      let realnum = num - 1;
     const input = document.getElementById("rolealign");
    const splited = input.innerHTML.split(" ");
  let result = input.innerHTML;
  let winner =  splited[realnum];
  result.replace(winner, `<span style="color:${color};"> ${winner} <span>`);
  console.log(result);
  input.innerHTML = result;
}

Let's say the string is Miki Mouse.

Nothing happens.

result - Stays as Miki Mouse
winner - Miki
splited - ["Miki", "Mouse"]
color - A value taken of out a color input.

Can someone please explain to me why my code doesn't work, and point me out to some other soultions? Thanks.

Mxm
  • 97
  • 1
  • 13
  • Possible duplicate of [Replace method doesn't work](https://stackoverflow.com/questions/1433212/replace-method-doesnt-work) – Kirk Larkin Nov 07 '18 at 10:05

1 Answers1

3

The problem is that the line

result.replace(winner, `<span style="color:${color};"> ${winner} <span>`);

does nothing - it creates a new string with the HTML markup, and then that new string is not assigned to anything, so it's never used again, and soon gets garbage collected. Primitives, including strings, are immutable, so you can't .replace in-place - you have to explicitly assign to a new variable:

function SpecialColor(num) {
  const color = document.getElementById(`alignColor${num}`).value;
  const realnum = num - 1;
  const input = document.getElementById("rolealign");
  const splited = input.innerHTML.split(" ");
  const result = input.innerHTML;
  const winner = splited[realnum];
  const htmlResult = result.replace(winner, `<span style="color:${color};"> ${winner} <span>`);
  console.log(htmlResult);
  input.innerHTML = htmlResult;
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320