Say I have a string below:
const input = `This is a link: /, this is another link: .`
How would I parse that string and output another string that looks as follows in js:
const output = `This is a link: <a href="/">/</a>, this is another link: <a href=";>;/a>.`
Say I have a string below:
const input = `This is a link: https://www.google./, this is another link: https://stackoverflow./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./">https://www.google./</a>, this is another link: <a href="https://stackoverflow./questions/ask">https://stackoverflow./questions/ask</a>.`
Share
Improve this question
asked Jan 14, 2021 at 21:47
svorugantisvoruganti
6821 gold badge7 silver badges30 bronze badges
2 Answers
Reset to default 5You will need help of regular expressions.
You can start here: https://developer.mozilla/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:
- https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
- https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Template_literals
And you can practice in general with this regular expression playground https://regexr./
const input = `This is a link: https://www.google./, this is another link: https://stackoverflow./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./, this is another link: https://stackoverflow./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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745322475a4622504.html
评论列表(0条)