Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
Darlyn Avatar asked Jun 28 '15 15:06

Darlyn


People also ask

What is {} called in Python?

In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

What is the purpose of the curly brackets {} in regular expression?

The curly brackets are used to match exactly n instances of the proceeding character or pattern. For example, "/x{2}/" matches "xx".

What is curly braces in node JS?

Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.


1 Answers

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 }
like image 101
Lucas Trzesniewski Avatar answered Sep 23 '22 11:09

Lucas Trzesniewski