javascript - 使用 jquery regex 函数显示匹配的字符串

标签 javascript jquery ajax regex

如何使用 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>

Jsfiddle Example

最佳答案

你可以这样做:

$("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();
    }
});

http://jsfiddle.net/D5uLE/1/

有两件事需要注意。您应该添加一个全局标志 g到你的正则表达式。然后你应该使用 String.match方法将为您提供找到的子字符串的数组:

["http://example1.com", "http://example2.com"]

然后您可以迭代这个数组并用它做任何您想做的事情。在上面的例子中,我只是用 <br> 加入它为了简单起见..

关于javascript - 使用 jquery regex 函数显示匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17504253/

相关文章:

ajax - 具有运球分页数据的 ionic 无限滚动?

javascript - 男性或女性复选框选择器

javascript - Bootstrap 嵌套折叠仅在父折叠时发生事件

javascript - 如何使用jquery检查 anchor 文本是否包含图像标签?

javascript - GitHub:如何为 ajax 请求设置 header ?

javascript - 提交表格后停留在同一页面

javascript - 从指令 AngularJS 更改 Controller 范围值

javascript - Bootstrap : Search Icon Button Inside Input Box separates from Inputbox at non-desktop Resolution

javascript - 将 Jquery UI Sortable 转换为表而不是 ul

javascript - 为什么等式的值最后没有定义?