Darlyn
Darlyn

Reputation: 4938

replacing curly brackets and text in it with node

I have a string

var str="Hello my name is {john/www.john.com} and welcome to my {site/www.site.com}."

i have extracted curly brackets and made an anchor tag out of them like

<a href="www.john.com">john</a>

What i am trying to do is replace curly brackets and content in them with these nodes. Is it possible using regExp? I have studied regExp on MDN but still cant figure out the way.

Upvotes: 9

Views: 6912

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51390

Sure it is:

var str = "Hello my name is {john/www.john.com} and welcome to my {site/www.site.com}.";

str = str.replace(/\{(.+?)\/(.+?)\}/g, function(m, label, url) {
    return '<a href="http://' + url + '">' + label + '</a>';
});

document.write(str);

The regex is:

\{(.+?)\/(.+?)\}
  • \{ matches {
  • (.+?) matches and captures anything (as few chars as possible, so up to the first /)
  • \/ matches /
  • (.+?) matches and captures anything up to }
  • \} matches }

Upvotes: 16

Related Questions