在 Javascript 中使链接可点击?

发布于 2024-08-26 22:00:43 字数 257 浏览 6 评论 0原文

字符串从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

单身狗的梦 2024-09-02 22:00:43

是的。最简单的方法是使用正则表达式将看起来像链接的内容替换为其链接的等效项。像这样的东西:(

node.innerHTML = node.innerHTML.replace(/(http:\/\/[^\s]+)/g, "<a href='$1'>$1</a>")

我的正则表达式有点生疏,所以你可能需要使用语法)。这只是一个简单的案例。您需要警惕此处的脚本注入(例如,如果我有 http://">)。解决此问题的一种方法是通过使用链接构建功能:

node.innerHTML = node.innerHTML.replace(/ ... /g, buildLink($1));

其中 buildLink() 可以检查以确保 URL 不包含任何恶意内容,

但是,RegEx-innerHTML 方法在大型文本上的表现不佳。 ,因为它会分解并重建节点的整个 HTML 内容 您也可以使用 DOM 方法来实现此目的:

  • 查找对文本节点的引用
  • 在内容中,查找 URL 的开始和结束索引
  • 使用 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:

node.innerHTML = node.innerHTML.replace(/(http:\/\/[^\s]+)/g, "<a href='$1'>$1</a>")

(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:

node.innerHTML = node.innerHTML.replace(/ ... /g, buildLink($1));

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:

  • Find reference to the text node
  • In the content, find start and end indexes of a URL
  • Use splitText() method to split the node into 3: before, link, after
  • Create an <a> node with the href that's the same as the link
  • Use insertBefore() to insert this <a> node before the link
  • Use appendChild() to move the link into the <a> node
﹏雨一样淡蓝的深情 2024-09-02 22:00:43

首先,“在 HTML 页面内”很困难,因为“页面”实际上是一棵 DOM 树(部分由文本节点组成,大部分由 HTML 元素组成)。

解决这个问题的最简单方法是定位内容丰富的文本节点。对于每个文本节点,应用如下所示的内容:

// we'll assume this is the string of a content-rich text node
var textNode = document.getElementById('contentNode');
textNode.innerHTML = textNode.innerHTML.replace(/(\s)(http:\/\/[^\s]+)(\s)/g, '$1<a href="$2">$2</a>$3');

顺便说一句:这里存在安全隐患。如果您从未经消毒的文本生成链接,则存在 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:

// we'll assume this is the string of a content-rich text node
var textNode = document.getElementById('contentNode');
textNode.innerHTML = textNode.innerHTML.replace(/(\s)(http:\/\/[^\s]+)(\s)/g, '$1<a href="$2">$2</a>$3');

BTW: there are security implications here. If you generate links from unsterilized text, there is the possibility of XSS.

○闲身 2024-09-02 22:00:43

我使用一个利用 regex(正则表达式)的函数来更轻松地执行此操作。下面链接了一些文档和一些正则表达式备忘单。

function linkfun(text, https) {
    if(https == "both") { // both
      var urlRegex = /(https?:\/\/[^\s]+)/g; // regex for both http:// and https://
      return text.replace(urlRegex, function(url) {
          return '<a href="' + url + '">' + url + '</a>'; // return the replaced text
      })
    }

    if(https == true) {
      var urlRegex = /(https:\/\/[^\s]+)/g; // regex for only https:// (notice the missing "?")
      return text.replace(urlRegex, function(url) {
          return '<a href="' + url + '">' + url + '</a>'; // return the replaced text
      })
    } else {
      var urlRegex = /(http:\/\/[^\s]+)/g; // regex for only http:// (notice the missing "?")
      return text.replace(urlRegex, function(url) {
          return '<a href="' + url + '">' + url + '</a>'; // return the replaced text
      })
    }
    // or alternatively
    // return text.replace(urlRegex, '<a href="$1">$1</a>')
}
<p id="text">Hi!! https://example.org is my favourite website, but http://example.net is also good. http://stackoverflow.com and https://stackexchange.com are cool. https://www.firefox.com is a web browser.<br><br>If you want to use this function multiple times on the same text, use <code>linkfun(...innerText, ...)</code> instead of <code>linkfun(...innerHTML, ...)</code></p>
<button onclick="document.getElementById('text').innerHTML = linkfun(document.getElementById('text').innerHTML, true);">Change just HTTPS</button>

<button onclick="document.getElementById('text').innerHTML = linkfun(document.getElementById('text').innerHTML, false);">Change just HTTP</button>

<button onclick="document.getElementById('text').innerHTML = linkfun(document.getElementById('text').innerHTML, 'both');">Change both</button>

您可以了解有关以下内容的更多信息:

- 正则表达式位于 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.

function linkfun(text, https) {
    if(https == "both") { // both
      var urlRegex = /(https?:\/\/[^\s]+)/g; // regex for both http:// and https://
      return text.replace(urlRegex, function(url) {
          return '<a href="' + url + '">' + url + '</a>'; // return the replaced text
      })
    }

    if(https == true) {
      var urlRegex = /(https:\/\/[^\s]+)/g; // regex for only https:// (notice the missing "?")
      return text.replace(urlRegex, function(url) {
          return '<a href="' + url + '">' + url + '</a>'; // return the replaced text
      })
    } else {
      var urlRegex = /(http:\/\/[^\s]+)/g; // regex for only http:// (notice the missing "?")
      return text.replace(urlRegex, function(url) {
          return '<a href="' + url + '">' + url + '</a>'; // return the replaced text
      })
    }
    // or alternatively
    // return text.replace(urlRegex, '<a href="$1">$1</a>')
}
<p id="text">Hi!! https://example.org is my favourite website, but http://example.net is also good. http://stackoverflow.com and https://stackexchange.com are cool. https://www.firefox.com is a web browser.<br><br>If you want to use this function multiple times on the same text, use <code>linkfun(...innerText, ...)</code> instead of <code>linkfun(...innerHTML, ...)</code></p>
<button onclick="document.getElementById('text').innerHTML = linkfun(document.getElementById('text').innerHTML, true);">Change just HTTPS</button>

<button onclick="document.getElementById('text').innerHTML = linkfun(document.getElementById('text').innerHTML, false);">Change just HTTP</button>

<button onclick="document.getElementById('text').innerHTML = linkfun(document.getElementById('text').innerHTML, 'both');">Change both</button>

You can learn more about:

- regex at mdn devdocs caniuse cheatsheet (rexegg) cheatsheet (mdn)

- string:replace at mdn devdocs caniuse

楠木可依 2024-09-02 22:00:43

对于 2023 年之后来到这里的所有人:不要为此编写正则表达式。 https://linkify.js.org/

To all people coming here after 2023: don't write regex for this. https://linkify.js.org/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文