javascript - 使用 JavaScript 检测文本中的 URL

标签 javascript regex url

有人对检测一组字符串中的 URL 有什么建议吗?

arrayOfStrings.forEach(function(string){
  // detect URLs in strings and do something swell,
  // like creating elements with links.
});

更新:我最终使用这个正则表达式进行链接检测……显然是几年后。

kLINK_DETECTION_REGEX = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gi

完整的助手(带有可选的 Handlebars 支持)位于 gist #1654670 .

最佳答案

首先,您需要一个匹配 url 的良好正则表达式。这很难做到。参见 here , herehere :

...almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.

Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible.

For example ::::: is a valid URL. The path is ":::::". A pretty stupid filename, but a valid filename.

Also, ///// is a valid URL. The netloc ("hostname") is "". The path is "///". Again, stupid. Also valid. This URL normalizes to "///" which is the equivalent.

Something like "bad://///worse/////" is perfectly valid. Dumb but valid.

无论如何,这个答案并不是要给你最好的正则表达式,而是证明如何使用 JavaScript 在文本中进行字符串换行。

好的,让我们只使用这个:/(https?:\/\/[^\s]+)/g

同样,这是一个糟糕的正则表达式。它会有很多误报。但是对于这个例子来说已经足够了。

function urlify(text) {
  var urlRegex = /(https?:\/\/[^\s]+)/g;
  return text.replace(urlRegex, function(url) {
    return '<a href="' + url + '">' + url + '</a>';
  })
  // or alternatively
  // return text.replace(urlRegex, '<a href="$1">$1</a>')
}

var text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
var html = urlify(text);

console.log(html)

// html now looks like:
// "Find me at <a href="http://www.example.com">http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>"

总而言之,尝试:

$$('#pad dl dd').each(function(element) {
    element.innerHTML = urlify(element.innerHTML);
});

关于javascript - 使用 JavaScript 检测文本中的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1500260/

相关文章:

javascript - 在 jQuery 中连续滚动 Div

python - %s 在正则表达式中表现出奇怪的行为

Python 正则表达式搜索或匹配不起作用

python - 在广泛的 Scrapy Web 爬虫中只允许内部链接

javascript - 类型错误 : props is undefined

javascript - 如何在饼图中添加和操作值?

javascript - QUnit 对比 Jasmine 和 TDD 对比。 BDD

html - 正则表达式 - 在 Dreamweaver 中查找和替换

url - CakePHP:高级 'SEO' 路由 - 如何保存旧 URL 更改帖子的路由,用于外部链接的 301 重定向

html <base> 不适用于 localhost 的 href