如何使用jquery正则表达式函数显示匹配的字符串:
var textarea = "There are two URLs: http://example1.com and http://example2.com";
var filter_url = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w\.-=?]*)*\/?/;
if (filter_url.test(textarea)) {
$('#show_match').html('// show matched URLs //');
$('#show_match').fadeIn();
}
结果:
<div id="show_match">http://example1.com http://example2.com</div>
答案 0 :(得分:2)
您可以这样做:
$("a#check").click(function () {
var textarea = "There are two URLs: http://example1.com and http://example2.com";
var filter_url = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w\.-=?]*)*\/?/g,
m;
if (m = textarea.match(filter_url)) {
$('#show_match').html(m.join('<br>'));
$('#show_match').fadeIn();
}
});
所以要注意两件事。您应该在正则表达式中添加全局标记g
。然后你应该使用String.match
方法,它将为你提供一系列找到的子串:
["http://example1.com", "http://example2.com"]
然后,您可以遍历此数组并使用它执行任何操作。在上面的示例中,为了简单起见,我刚刚使用<br>
加入了它。