在 Javascript 中使链接可点击?
字符串从 Javascript 转换为字符串
Then go to http:/example.com/ and foo the bar!
?
Then go to <a href="http://example.com">example.com</a> and foo the bar!
有没有一种简单的方法可以在现有 HTML 页面中将
Is there an simple way of turning a string from
Then go to http:/example.com/ and foo the bar!
into
Then go to <a href="http://example.com">example.com</a> and foo the bar!
in Javascript within an existing HTML page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。最简单的方法是使用正则表达式将看起来像链接的内容替换为其链接的等效项。像这样的东西:(
我的正则表达式有点生疏,所以你可能需要使用语法)。这只是一个简单的案例。您需要警惕此处的脚本注入(例如,如果我有
http://">
)。解决此问题的一种方法是通过使用链接构建功能:其中
buildLink()
可以检查以确保 URL 不包含任何恶意内容,但是,RegEx-innerHTML 方法在大型文本上的表现不佳。 ,因为它会分解并重建节点的整个 HTML 内容 您也可以使用 DOM 方法来实现此目的:
splitText()。
方法将节点拆分为 3 个:before、link、after节点,其
href
与链接相同insertBefore()
在链接之前插入此节点
appendChild()
将链接移动到中
节点Yes. The simplest way is to use a regular expressions to substitute things that look like a link for their linked equivalents. Something like:
(my RegEx is a little rusty, so you may need to play with the syntax). This is just a simple case. You need to be wary of script injection here (for example if I have
http://"><script>doevil()</script>
). One way to work around this is by using a link building function:Where
buildLink()
can check to make sure the URL doesn't contain anything malicious.However, the RegEx-innerHTML method will not perform very well on large bodies of text though, since it tears down and rebuilds the entire HTML content of the node. You can achieve this with DOM methods as well:
splitText()
method to split the node into 3: before, link, after<a>
node with thehref
that's the same as the linkinsertBefore()
to insert this<a>
node before the linkappendChild()
to move the link into the<a>
node首先,“在 HTML 页面内”很困难,因为“页面”实际上是一棵 DOM 树(部分由文本节点组成,大部分由 HTML 元素组成)。
解决这个问题的最简单方法是定位内容丰富的文本节点。对于每个文本节点,应用如下所示的内容:
顺便说一句:这里存在安全隐患。如果您从未经消毒的文本生成链接,则存在 XSS 的可能性。
First, "within an HTML page" is difficult because a "page" is actually a DOM tree (which is partially composed of text nodes and mostly composed of HTML elements).
The easiest way to approach this problem would be to target content-rich text nodes. For each text node, apply something like this:
BTW: there are security implications here. If you generate links from unsterilized text, there is the possibility of XSS.
我使用一个利用 regex(正则表达式)的函数来更轻松地执行此操作。下面链接了一些文档和一些正则表达式备忘单。
您可以了解有关以下内容的更多信息:
- 正则表达式位于 mdn 开发文档 caniuse 备忘单 (rexegg) cheatsheet (mdn)
- string:replace at mdn devdocs 犬类
I use a function utilizing regex (regular expressions) to make it easier to do this. Some docs and some regex cheatsheets are linked below.
You can learn more about:
- regex at mdn devdocs caniuse cheatsheet (rexegg) cheatsheet (mdn)
- string:replace at mdn devdocs caniuse
对于 2023 年之后来到这里的所有人:不要为此编写正则表达式。 https://linkify.js.org/
To all people coming here after 2023: don't write regex for this. https://linkify.js.org/