javascript的防弹URL匹配正则表达式

bulletproof URL matching regex for javascript?

本文关键字:正则表达式 URL 防弹 javascript      更新时间:2023-09-26

有人能帮我找到一个匹配任何和所有URL模式的正则表达式模式吗?我找到了几个,但它们似乎有缺陷。

我对匹配URL中的任何单个元素(如域或其他)都不感兴趣,我只需要从文本字符串中可靠地提取一个URL的整体,然后输出一个可用的URL(意味着它前面应该总是有一个http://)

以下是我想匹配的示例URL

http://www.google.com
www.google.com
code.google.com
http://code.google.com/hosting/search?q=label%3aPython

注意到有些缺少http://标签,所以如果它们缺少,我想添加这些标签

功能的最终结果应该是

1: http://www.google.com
2: http://www.google.com
3: http://code.google.com
4: http://code.google.com/hosting/search?q=label%3aPython

这是我的建议:

<script>
var html = 'http://www.google.com';
html += ''rwww.google.com ';
html += ''rcode.google.com';
html += ''rhttp://code.google.com/hosting/search?q=label%3aPython';
var regex = /(https?:'/'/)?('w+'.?)+('/[a-zA-Z0-9'?%=_'-'+'/]+)?/gi;
alert('before replace:');
alert(html);
html = html.replace(regex, function (match, capture) {
    if (capture) {
        return match
    }
    else {
        return 'http://' + match;
    }
});
alert('after replace:');
alert(html);
</script>