4

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>.`

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but is there a library to already do this?
I would recommend this framework vanilla-js.com Just joking 😂 Plain Javascript is quite good and performant doing this.
Ok got down the regex expression and learned about the replace method, however, how do I replace it with <a> element? replace(regex, what goes here?)
"what goes here?" => (x)=>'<a href="'+x+'">'+x+'</a>'
2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.