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>" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |