最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论