Leela Hari Prasad. R
Leela Hari Prasad. R

Reputation: 59

How to find using jQuery to find text that contain a specific text

I want to get the value of steve only in alert like this.

<div class="value">333</div>

Below is my code

var a = $("p:contains('Steve')").text();
alert('<div class="value">' + a + '</div>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  John: 111
  <br>Sam: 222
  <br>Steve: 333
</p>

Upvotes: 0

Views: 41

Answers (1)

empiric
empiric

Reputation: 7878

This will work (assuming the arragment of the characters and the digits will stay the same):

var match = $('p').text().match(/Steve\:\s(\d+)/);
$('.value').text(match[1]);
.value{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
    John: 111 <br>
    Sam: 222<br>
    Steve: 333
</p>
<div class="value"></div>

What I do here:

  • get the text (without markup) from the paragraph
  • match it against a regex
    • find the word Steve followed by a colon and capture the digits after that
  • set the content of the div.value with the content of the capture group

Be aware that this is just a quick example. Changes to your markup and the content can change the result. (e.g. if more than one match is found)

Here you will find an explanation of the regex I used.


Example

Upvotes: 1

Related Questions