gpt4 book ai didi

javascript - jQuery 使用 Regex 在文本中查找链接,但如果链接在引号中则排除

转载 作者:行者123 更新时间:2023-11-29 11:02:33 27 4
gpt4 key购买 nike

我正在使用 jQuery 和 Regex 在文本字符串中搜索 http 或 https,并将该字符串转换为 URL。如果它以引号开头,我需要代码来跳过该字符串。

下面是我的代码:

// Get the content
var str = jQuery(this).html();

// Set the regex string
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '<a href="' + url + '">' + clean_url + '</a>';
})

jQuery(this).html(replaced_text);

这是我的问题的一个例子:

文字The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter <a href="https://twitter.com/abcdef">@Abcdef</a>.

当前代码成功找到以 http 或 https 开头的文本并将其转换为 URL,但它也转换了 twitter URL。如果文本以引号开头或在标签内等,我需要忽略该文本...

非常感谢任何帮助

最佳答案

如何将 [^"'] 添加到 exp 变量?

var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

片段:

// Get the content
var str = jQuery("#text2replace").html();

// Set the regex string
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '<a href="' + url + '">' + clean_url + '</a>';
})

jQuery("#text2replace").html(replaced_text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="text2replace">
The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter <a href="https://twitter.com/abcdef">@Abcdef</a>.
</div>

关于javascript - jQuery 使用 Regex 在文本中查找链接,但如果链接在引号中则排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44572119/

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