2017-06-15 63 views
3

我正在使用jQuery和正则表达式搜索一个文本字符串为http或https并将字符串转换为URL。如果以引号开头,我需要代码跳过该字符串。jQuery使用正则表达式来查找文本中的链接,但排除,如果链接是在引号

下面

是我的代码:

// 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。我需要忽略的文本,如果它以引号开始或者是一个标签内,等...

任何帮助深表感谢

回答

2

怎么样添加[^"']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>

+0

这正是我需要的。谢谢! @lpg – Jason

+0

如果链接位于字符串的起始处,它将不会与当前的正则表达式匹配。 –

0

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

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