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.
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.
The curly brackets are used to match exactly n instances of the proceeding character or pattern. For example, "/x{2}/" matches "xx".
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With