I have a description from database coming like this :
"And here is the {{dog}} which is chasing the {{cat}}"
And instead of having {{dog}} I want to replace it by <span class="dog"/>
I tried this : My Attempt
I know how I can exctract but I don't know how to replace these parts only and then do my display.
Thanks you!
EDIT :
var input = "And here is the {{dog}} which is chasing the {{cat}}";
var regex = /{{(.*?)}}/g;
var matches, output = [];
while (matches = regex.exec(input)) {
output.push(matches[1]);
}
I want my final string to be :
And here is the <span class="dog"/> which is chasing the <span class='cat'/>
You could use a capturing group like this:
$1 indicates the text matched within the parentheses (capturing group) and can be used in replace (MDN)
const str = "And here is the {{dog}} which is chasing the {{cat}}"
const newStr = str.replace(/{{(\w+)}}/g, "<span class='$1' />")
console.log(newStr)
Use regex to replace and capture the text you wish.
const data = "And here is the {{dog}} which is chasing the {{cat}}";
const res = data.replace(/\{{2}([a-z]+)\}{2}/g, '<span class="$1">$1</span>');
document.body.innerHTML = res;
span {
background-color: blue;
color: white;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With