如何使用 jquery regex 函数显示匹配的字符串:
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>
最佳答案
你可以这样做:
$("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>
加入它为了简单起见..
关于javascript - 使用 jquery regex 函数显示匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17504253/