假设我在下面有一个字符串:
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
你可以检查这个:What is a good regular expression to match a 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
您可以使用这个正则表达式 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)
关于javascript - 如何将带有链接的字符串解析为html链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65727356/