I am working with an HTML string and my goal is to add an id
attribute to all <form>
tags that do not already have one.
However, I am encountering an issue when a <form>
tag's child already has an id.
<html>
<body>
<form class="class1">
<input id="hello" type="text"/>
</form>
<form class="bye">
bye
<input type="text"/>
</form>
</body>
</html>
In the first <form>
, there is an <input>
with an id already, so it does not get a new id added. I only want to target the <form>
element itself, but it seems to be checking the entire <form>
tag.
This is what I have tried:
const htmlString = `<html>
<body>
<form class="class1">
<input id="hello" type="text"/>
</form>
<form class="bye">
bye
<input type="text"/>
</form>
</body>
</html>`
const idPrefix = "MyPrefix";
let modifiedHtmlString = htmlString;
let formIndex = 1;
let startIndex = modifiedHtmlString.indexOf("<form");
while (startIndex !== -1) {
const endIndex = modifiedHtmlString.indexOf("</form>", startIndex);
const formTag = modifiedHtmlString.slice(startIndex, endIndex);
if (!formTag.includes("id=")) {
const modifiedFormTag = formTag.replace("<form", `<form id="${idPrefix}${formIndex}"`);
modifiedHtmlString = modifiedHtmlString.replace(formTag, modifiedFormTag);
formIndex++;
}
startIndex = modifiedHtmlString.indexOf("<form", endIndex);
}
console.log(modifiedHtmlString);