如何将url替换为除youtube url之外的锚点



我正在编写一个函数,用于检查HTTP链接,如果存在,则用锚标记替换它们。如果有一个YouTube URL,它会用iframe替换它。我很难完成它,因为我不知道如何为那些不是YouTube URL的URL添加锚。

以下是的功能

export const renderLinkWithText = (text = '') => {
// eslint-disable-next-line
const replacePattern1 = /(b(https?|ftp)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gim
const newText = text.replace(replacePattern1, '<a class="anchor_link" target="_blank" href="$1">$1</a> ')
return newText.replace(/nr?/g, '<br />').replace(/(?:https://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch?.*v=)?(w+)/g, '<iframe width="100%" height="350px" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>')
}

您可能希望在排除youtube URL的第一个模式中包含一个负前瞻。大致如下:

(?!(www.)?(youtube.com|youtu.be))

整个模式将变成:

(b(https?|ftp)://(?!(www.)?(youtube.com|youtu.be))[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])

编辑:我已经更正了最初的答案,你可以在线测试你的正则表达式。https://regex101.com/因为一个人接受了以上。

最新更新