0

I want to find and replace strings in html and replace them as tags.
from my name is ron and his name is ben
to my name is <b>ron</b> and his name is <b>ben</b>

Here is my code, works partially: https://stackblitz.com/edit/react-gjriyz

export default function App() {
  const arr = ["ron", "ben"];
  const str = "my name is ron and his name is ben";
  let res = "";
  for (var i in arr) {
    res = str.replace(arr[i], "<b>" + arr[i] + "</b>");
  }
  return (
    <div className="App">
      <span dangerouslySetInnerHTML={{ __html: res }} /> <br />
      <br /> 
      expected result: <br />
      my name is <b>ron</b> and his name is <b>ben</b>
    </div>
  );
}
SexyMF
  • 10,657
  • 33
  • 102
  • 206

2 Answers2

1

You are only ever updating res from the original string versus incrementally updating res, so the last replace operation trumps all.

export default function App() {
  const arr = ["ron", "ben"];
  const str = "my name is ron and his name is ben";
  let res = str;
  for (var i in arr) {
    // iterate on res, not str
    // res = str.replace(arr[i], "<b>" + arr[i] + "</b>");
    res = res.replace(arr[i], "<b>" + arr[i] + "</b>");
  }
  return (
    <div className="App">
      <span dangerouslySetInnerHTML={{ __html: res }} /> <br />
      <br /> 
      expected result: <br />
      my name is <b>ron</b> and his name is <b>ben</b>
    </div>
  );
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • This is correct, you are replacing str in the first loop, and then replacing the original value again in the second. This ignores the changes made in the first – Richard Price Mar 30 '20 at 07:34
0

I think the problem is that, you are not concatenating the results here.

 let res = "";
  for (var i in arr) {
    res = str.replace(arr[i], "<b>" + arr[i] + "</b>");
  }

This must be like below.

 let res = str;
  for (var i in arr) {
    res = res.replace(arr[i], "<b>" + arr[i] + "</b>");
  }
Praveenkumar
  • 2,056
  • 1
  • 9
  • 18