javascript - Jquery 字符串与正则表达式匹配不起作用

标签 javascript jquery regex

想要搜索文本并获取匹配项数:

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    <script type="text/javascript">
        function searchText(text) {
            var pattern = new RegExp("/" + text + "/g");
            var totalMatchCount = ($('Test').text().match(pattern) || []).length;
            alert(totalMatchCount)
        }
    </script>

</head>

<body>

    <div id="Test">

        2015-11-05 22:01:00,062                      WARN  [] (Thread-1169 (HornetQ-client-global-threads-643998766)) The license you are using has expired or is bad.  value: -5
        2015-11-05 22:02:00,026                      WARN  [] (Thread-1165 (-client-global-threads-643998766)) The license you are using has expired or is bad.  value: -5
        2015-11-05 22:03:00,049                      WARN  [] (Thread-1180 (-client-global-threads-643998766)) The license you are using has expired or is bad.  value: -5
    </div>

    <button onclick="searchText('WARN')">Search</button>
</body>

</html>

我正在搜索 WARN 单词并使用 RegExp() 方法作为模式, 但它不起作用。

最佳答案

两个问题:

  1. varpattern = new RegExp("/"+ text + "/g"); 更改为 varpattern = new RegExp(text, "g"); RegExp 期望标志用作第二个参数
  2. 选择器不正确。 $('测试').text().。未使用 id 选择器 $('#Test').text()。

function searchText(text) {
  var pattern = new RegExp(text, "g");
  var totalMatchCount = ($('#Test').text().match(pattern) || []).length;

  console.log(totalMatchCount);
  document.getElementById('result').innerHTML = JSON.stringify($('#Test').text().match(pattern), 0, 4);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Test">

  2015-11-05 22:01:00,062 WARN [dms.framework.licensing.LicenseManager] (Thread-1169 (HornetQ-client-global-threads-643998766)) The license you are using has expired or is bad. value: -5 2015-11-05 22:02:00,026 WARN [dms.framework.licensing.LicenseManager]
  (Thread-1165 (HornetQ-client-global-threads-643998766)) The license you are using has expired or is bad. value: -5 2015-11-05 22:03:00,049 WARN [dms.framework.licensing.LicenseManager] (Thread-1180 (HornetQ-client-global-threads-643998766)) The license
  you are using has expired or is bad. value: -5 2015-11-05 22:04:00,029
</div>

<button onclick="searchText('WARN')">Search</button>

<hr />
<pre id="result"></pre>

关于javascript - Jquery 字符串与正则表达式匹配不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561281/

相关文章:

c# - 使用正则表达式从字符串中检索数字

python - 组织文件并将其复制到新文件夹

javascript - 括号内的正则表达式匹配

javascript - 选中/取消选中 parent 和 child

javascript - 如何对 <div> 进行排序(升序和降序)并识别它们的状态?

javascript - 中间的 Ion.RangeSlider 颜色

javascript - 如何根据表中的用户链接点击生成新的 HTML 页面?

jquery - 让一个查询加载大量数据更有效,还是让多个查询加载较小的数据 block 更有效?

javascript - 如果图像已经加载,如何传递 .load() ?

javascript - 来自 http 409 的 Ajax 解析响应