Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: How to replace the matched text with a HTML element in JavaScript? [duplicate]

Tags:

javascript

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'/>

like image 902
Zeyukan Ich' Avatar asked Mar 24 '26 16:03

Zeyukan Ich'


2 Answers

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)
like image 125
adiga Avatar answered Mar 27 '26 04:03

adiga


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;
}
like image 21
kemicofa ghost Avatar answered Mar 27 '26 04:03

kemicofa ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!