Say I have a string below:
const input = `This is a link: https://www.google.com/, this is another link: https://stackoverflow.com/questions/ask.`
How would I parse that string and output another string that looks as follows in js:
const output = `This is a link: <a href="https://www.google.com/">https://www.google.com/</a>, this is another link: <a href="https://stackoverflow.com/questions/ask">https://stackoverflow.com/questions/ask</a>.`
You will need help of regular expressions.
You can start here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
You can check this: What is a good regular expression to match a URL?
From here you should capture the coincident regular expression and use those matches to replace it on the original input string.
You can go with a classical String replace taking advantage of the Template literals building the replacement using the same replaced text.
Interesting references about this two terms:
And you can practice in general with this regular expression playground https://regexr.com/
const input = `This is a link: https://www.google.com/, this is another link: https://stackoverflow.com/questions/ask.`
const urlRegex = /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))/g;
const matches = input.match(urlRegex);
let output = input;
for(let match of matches){
output = output.replace(match, `<a href="${match}">${match}</a>`);
}
console.log(output)
Here is a one liner:
const input = `This is a link: https://www.google.com/, this is another link: https://stackoverflow.com/questions/ask.`;
let output = input.replace(/(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))/g, (x)=>'<a href="'+x+'">'+x+'</a>');
console.log(output);
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