Replacing curly braces and text in it with node

I have a line

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

      

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

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

      

What I'm trying to do is replace the curly braces and the content in them with these nodes. Is regExp possible? I've looked into regExp on MDN, but still can't figure out how to do it.

+3


source to share


1 answer


Of course 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);
      

Run code




Regular expression:

\{(.+?)\/(.+?)\}

      

  • \{

    corresponds {

  • (.+?)

    matches and captures anything (as few characters as possible, up to the first /

    )
  • \/

    corresponds /

  • (.+?)

    matches and fixes everything before }

  • \}

    corresponds }

+8


source







All Articles