Remplace with regExp


html"<div> <h1> {{question}} </h1> 
<ul>
    <li>{{choice1}}</li>
    <li>{{choice2}}</li>
    <li>{{choice3}}</li>
    <li>{{choice4}}</li>
</ul>     
</div>"
randomChoise
 2
newCode"<div> <h1> {{question}} </h1> 
<ul>
    <li>{{choice1}}</li>
    <li class='selected'>{{choice2}}</li>
    <li>{{choice3}}</li>
    <li>{{choice4}}</li>
</ul>     
</div>"
const html = `<div> <h1> {{question}} </h1>
<ul>
<li>{{choice1}}</li>
<li>{{choice2}}</li>
<li>{{choice3}}</li>
<li>{{choice4}}</li>
</ul>
</div>`;
const randomChoise = (html, tagName, pos) => {
const regExp = new RegExp(`<${tagName}`, 'g');
let nbMatch = 0;
let newHTML = html.replace(regExp, function (match) {
if (nbMatch++ == pos) {
return `${match} class='selected'`
} else {
return match;
}
})
return newHTML;
}
const newCode = randomChoise(html, 'li', 2);
console.log(newCode)
view raw remplace.js hosted with ❤ by GitHub