-2
var HTMLTest = `blablabla <h1 id="Title">Porsche 911 GT3 RS</h1> blablabla`

Ok so i got a huge HTML string which is a full HTML page with style and all and I want to edit the part with the id Title inside my string. How can I do it using only basic Javascript ? If it's possible

I tried to find and replace text directly in my string but the text will change at each iteration of my loop so I can't use this.

Lixe
  • 1
  • 1
  • 2
    This should rather be done using a DOM parser than via string manipulation, to begin with. – CBroe Mar 16 '23 at 13:49
  • That's what I understood but I am restricted by my intership's boss – Lixe Mar 16 '23 at 13:50
  • 2
    _"but the text will change at each iteration of my loop "_ - what "loop"? This currently lacks context. – CBroe Mar 16 '23 at 13:51
  • It's been a long time since I've looked for a duplicate that turned up [this classic](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). As an aside... If technical leadership is limiting the tools you can use, perhaps technical leadership has suggestions on how you can use the tools they allow? – David Mar 16 '23 at 13:52
  • I am in a SetInterval function to scan QRCodes, i need to put the data in my HTML string each iteration, which will change everytime – Lixe Mar 16 '23 at 13:53
  • 1
    What *exactly* are your restrictions? "basic Javascript" is too vague. Do you consider regular expressions as "basic javascript"? What about `new DOM Parser()` (as per provided answer) - is that "basic javascript"? What about `.split()`? – freedomn-m Mar 16 '23 at 13:53
  • Here's a *"basic javascript"* solution - but it has so many caveats that it's unusable outside your explicit scenario (specifically that you only have 1 `h1`), so not worth an answer by itself and there will be better solutions, depending on the restrictions: `HTMLTest = HTMLTest.split('

    ')[0] + '

    ' + new_title + '

    ' + HTMLTest.split("")[1];`
    – freedomn-m Mar 16 '23 at 13:58
  • I've tried to use the DOM Parser anyway, sorry for your time guys. But i guess i'm missing something – Lixe Mar 16 '23 at 14:00

1 Answers1

2

Use DOMParser:

let htmlStr = `blablabla <h1 id="Title">Porsche 911 GT3 RS</h1> blablabla`;
let doc = new DOMParser().parseFromString(htmlStr, "text/html");
doc.getElementById("Title").textContent = 'New title text';
console.log(doc.body.innerHTML);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Okey well I've used this and converted it back to a String, sorry for the inconvenience/duplicate and thanks guys ! – Lixe Mar 16 '23 at 14:10