javascript - How to parse string with links into html links - Stack Overflow

Say I have a string below:const input = `This is a link: , this is another link: .`How would I parse

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
Add a ment  | 

2 Answers 2

Reset to default 5

You 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信