JavaScript function to identify URL and make them clickable

Viewed 98

I have a requirement , my client send me a string. for the links he is sending link title in squre brackets and link with bracket. like below,

[Google](https://www.google.com/)

I need get that value and make it clickable Google . adding like below and replace that to the original text.

<a href = "' + title + '" target="_blank">' + url + '</a>'

can anyone suggest better way of doing this with JavaScript regex.

4 Answers

Looks like Markdown formatting, so you could use a markdown library like Marked to parse and render it:

const s = '[Google](https://www.google.com/) ';

document.getElementById('content').innerHTML = marked(s);
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div id="content"></div>

Can be done with String replace function.

Regex: /\[(.*)\]\s*\((.*)\)/g

Replacer: <a href = "$2" target="_blank">$1</a>

const str = `Lorem ipsum. [Google](https://www.google.com/). Sample text.`

const output = replaceWithLinks(str);

console.log(output);

function replaceWithLinks(str) {
    return str.replace(/\[(.*)\]\s*\((.*)\)/g, '<a href="$2" target="_blank">$1</a>')
}

In HTML file:

<h1 id="header"></h1>

In Js File:

const myString = "[Google](https://www.google.com/)";
const show = myString.match(/\[(.*?)\]/); // it return two things. The first is with bracket and the second one is without bracket you have to use without bracket.
const url = myString.match(/\((.*?)\)/);
document.getElementById("header").innerHTML = `<a href="${url[1]}" target="_blank">${show[1]}</a>`;

You have to use regular expression. To get information about regular expression read MDN.

Get the first index value and show it to the UI.

Regexp is very handy for this purpose. just copy below code to F12 console for a preview

"text before [Google](https://www.google.com/) and after".replace(/\[(.*?)\]\((.*?)\)/gm, '<a href="$2" target="_blank">$1</a>')

ps: the code copy from a simple markdown parser

Related