【问题标题】:Check whether a URL contains www or https:// for RegEx检查 URL 是否包含用于 RegEx 的 www 或 https://
【发布时间】:2019-10-24 10:04:46
【问题描述】:

我有一个场景,我想检查一个字符串是否包含一个 url 并使其可点击。我使用正则表达式将其转换为 url。但它只适用于http。我也想为 wwww 制作它。在我拥有的正则表达式中,我可以添加 htttp 或删除 http 以在 url 中包含 www。 我已将代码粘贴在 JSfiddle 中

JSFiddle

var convertTextToHTML = $("#systemNotificationMsg").text();
var conversation = convertTextToHTML.replace(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/, function(text, link) {
   return '<a href="http://'+ link +'"> ' + link + ' </a>';
});

【问题讨论】:

标签: javascript jquery regex


【解决方案1】:

检查一下,您必须进行全局匹配,您的正则表达式正在寻找返回的第一个匹配项。您必须在正则表达式中匹配多个 /gi

	var convertTextToHTML = $("#systemNotificationMsg").text();
var conversation = convertTextToHTML.replace(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/gi, function(text, link) {
	console.log("Link in text: "+ link);
   return '<a href="http://'+ link +'"> ' + link + ' </a>';
});
$("#systemNotificationMsg").html(conversation);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="systemNotificationMsg">
This message contains a link to www.google.com/hungerbox
and another to www.google.com so this is the example
</div>

【讨论】:

  • 请看第二个链接。它没有被转换为可点击的链接
  • 我已经更新了答案,您现在可以检查两个链接是否都转换为hyperlinks。我希望它有所帮助。
【解决方案2】:

这可以通过稍微简单的正则表达式来实现。

我在这里更新了 JSFiddle:

https://jsfiddle.net/Lxnfq95b/1/

现在的正则表达式是:

/(www|https?)([^\s]+)/g

请注意/g 是必需的,以使其全部替换。

(www|https?) 将匹配 www.或 http(s) 链接。

([^\s]+) 将使正则表达式继续运行,直到遇到空格字符。

【讨论】:

  • @tkamath99 请检查更新后的答案 - 我误解了你。
  • Dawson... 当文本中已经存在 http:// 时,我遇到了问题。它附加另一个 http:// 导致 URL 错误。如果已经存在,是否有任何条件检查以删除 http://?
猜你喜欢
  • 2012-05-02
  • 2011-12-02
  • 2012-10-31
  • 2021-01-06
  • 2018-02-05
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多