You can utilize the match
function with the regex pattern /(?<=(\[|\())([^\])]+)/g
var matches = "[url.com](url)".match(/(?<=(\[|\())([^\])]+)/g) ; //["url.com", "url"]
Next, apply matches
to create an anchor tag like so:
var aHTML = "";
if (matches && matches.length == 2)
{
aHTML = '<a href="' + matches[0] + '">' + matches[0] + '</a>'
}
Update
If you have a string formatted in this way and need to replace it inline, use the following:
var getLink = (str) => {
var matches = str.match(/(?<=(\[|\())([^\])]+)/g);
var aHTML = "";
if (matches && matches.length == 2) {
aHTML = '<a href="' + matches[0] + '">' + matches[0] + '</a>'
}
return aHTML;
};
var replaceInline = (str) => {
return str.replace( /\[[^\]]+\]\([^)]+\)/g, r => getLink(r) );
};
Example
var getLink = (str) => {
var matches = str.match(/(?<=(\[|\())([^\])]+)/g);
var aHTML = "";
if (matches && matches.length == 2) {
aHTML = '<a href="' + matches[0] + '">' + matches[0] + '</a>'
}
return aHTML;
};
var replaceInline = (str) => {
return str.replace( /\[[^\]]+\]\([^)]+\)/g, r => getLink(r) );
};
var sample = "Here is a link [url.com](url) inline";
console.log( replaceInline(sample) );