gpt4 book ai didi

javascript - 检查URL是否包含www或https ://for RegEx

转载 作者:行者123 更新时间:2023-11-28 14:13:52 26 4
gpt4 key购买 nike

我有一个场景,我想检查字符串是否包含 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>';
});

最佳答案

看看这个,你必须进行全局匹配,你的正则表达式正在找到第一个匹配返回。您必须在正则表达式中匹配多个 /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>

关于javascript - 检查URL是否包含www或https ://for RegEx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58538941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com