3

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

2
  • 1
    This is displaying an image! Sorry for syntax, I'm using React that's why I wrote <span class="dog"/>. I just chose span but it would be an image or whatever. Commented Feb 5, 2019 at 15:08
  • 1
    "I tried this : My Attempt" The way SO works, your whole question (including any necessary code) has to be in your question, not just linked. Two reasons: People shouldn't have to go off-site to help you; and links rot, making the question and its answers useless to people in the future. Please put a minimal reproducible example in the question. More: How do I ask a good question? and Something in my web site or project doesn't work. Can I just paste a link to it? Commented Feb 5, 2019 at 15:10

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.