0

For example, if i wanted to replace "mystring" with "myotherstring" in

<!DOCTYPE html>
<html>
<body>
<h1 id="mystring">mystring</h1>
<p>mystring</p>
<script>mystring javascript blah</script>
</body>
</html>

how could i only replace it in the <h1> and <p> tags with javascript, or can i do it without js?

Fexo
  • 23
  • 4
  • Why are you treating HTML as text? HTML is parsed by browsers, you don't need to parse it youtself – Christian Vincenzo Traina Sep 18 '22 at 09:55
  • A way to do this is to use regex. So you can tell you only replace mystring when it's circled with > and – Guillaume Sep 18 '22 at 09:58
  • 2
    @Guillaume rethink your suggestion. You should **never use regular expressions to parse HTML**, rather a proper inbuilt [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser). [More info](https://stackoverflow.com/q/1732348/383904) – Roko C. Buljan Sep 18 '22 at 10:05
  • @RokoC.Buljan You're right, my approach expected this html to be a whole text to be converted uing JS – Guillaume Sep 18 '22 at 10:10
  • @Guillaume that's not *any kind of text*. It's HTML, where it's absolutely normal to have i.e: stuff like: `

    mystring

    ` or stull like `
    – Roko C. Buljan Sep 18 '22 at 10:12
  • @Christian Vincenzo TrainaI wouldn't if I didn't have to, but in this case I don't have control over the actual html so i want to change the string – Fexo Sep 18 '22 at 14:51
  • @Fexo you accepted Jamie answer, that's what I meant :) – Christian Vincenzo Traina Sep 19 '22 at 07:17

1 Answers1

1

You can select the specific tags you're interested in and do the replacement.

document.querySelectorAll("h1, p").forEach((el) => {
      el.textContent = el.textContent.replace(/\bmystring\b/g, "myotherstring");
    });

https://codesandbox.io/s/unruffled-firefly-ssb8cj?file=/src/index.js
Read more about the \b (Word Boundary)

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162