简体   繁体   中英

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.

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM