如何将带有链接的字符串解析为html链接



假设下面有一个字符串:

const input = `This is a link: https://www.google.com/, this is another link: https://stackoverflow.com/questions/ask.`

我如何解析该字符串并输出另一个字符串,在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>.`

你需要正则表达式的帮助。

你可以从这里开始:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

你可以检查一下:什么是匹配URL的好的正则表达式?

从这里开始,您应该捕获符合的正则表达式,并使用这些匹配来替换原始输入字符串上的正则表达式。

你可以使用经典的字符串替换,利用模板字面量使用相同的被替换文本构建替换。

关于这两个术语的有趣参考:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

一般你可以用这个正则表达式操场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)

一行:

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

最新更新