This is a follow up question of Replace HTML tag with string that contains tag attribute.
This time I would like to do the opposite process and replace occurrences of ${something.foo.bar} back to <input type="button" disabled="" data-value="something.foo.bar" value="foo.bar" />.
For example consider this string:
"the quick ${something.brown.fox} jumps over the ${something.lazy.dog}"
The end result should be:
the quick <input type="button" disabled="" data-value="something.brown.fox" value="brown.fox" /> jumps over the <input type="button" disabled="" data-value="something.lazy.dog" value="lazy.dog" />
Note that something. is a known prefix and will always be present inside the curly braces, so the input data-value should be the value between the braces and the input value attribute should contain the value without the prefix.
I've tried to solve it with multiple chaining of Regex match and replaceAll but didn't managed to get the desired outcome.
Help appreciated.
You can make it simply using String.replace:
const s = "the quick ${something.brown.fox} jumps over the ${something.lazy.dog}"
const res = s.replace(/\$\{([^}]+)\}/g, (x, y) => {
const [prefix, ...rest] = y.split('.')
return `<input type="button" disabled="" data-value="${y}" value="${rest.join('.')}" />`
})
console.log(res)