0

want to search the text and get the no of matches :

<!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>

I'm searching for WARN word and used RegExp() method for pattern, but its not working.

1 Answer 1

1

Two Issues:

  1. Change var pattern = new RegExp("/" + text + "/g"); to var pattern = new RegExp(text, "g"); RegExp expect the flags to be used as second parameter
  2. Incorrect selector. $('Test').text().. No id selector used $('#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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Tushar, I am not aware of first issue. Its working as expected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.