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

时间:2017-06-15 16:02:40

标签: javascript jquery regex

我正在使用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。我需要忽略文本,如果它以引号开头或在标签内等等......

非常感谢任何帮助

3 个答案:

答案 0 :(得分:2)

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

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

段:

&#13;
&#13;
// 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);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果你真的只想忽略引号,这可能会有所帮助:

var replaced_text = $("#selector").html().replace(/([^"])(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '$1<a href="$2">$2</a>');

答案 2 :(得分:0)

这对我有用:

这将识别URL并将其转换为超链接,但将忽略用DROP TASK schedule_regioni; CREATE TASK schedule_regioni WAREHOUSE = COMPUTE_WH SCHEDULE = 'USING CRON 42 18 9 9 * Europe/Rome' COMMENT = 'Test Schedule' AS call sp_upload_c19_regioni(); (引号)引起的URL。

有关工作示例,请参见下面的代码或此jsfiddle

示例HTML:

"

RegEX:

<ul class="js-replaceUrls">
    <li>
        www.link-only-www.com
    </li>
    <li>
        http://link-starts-with-HTTP.com
    </li>
    <li>
        https://www.link-starts-with-https-and-www.com
    </li>

    <a href="https://link-starts-with-https.com">
        Link in anchor tag
    </a>
</ul>

jQuery:

/(([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+_\-\.%=&amp;]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gmi

有关工作示例,请参见此jsfiddle