DjH
DjH

Reputation: 1498

Javascript/JQuery split paragraph to get a single word

I'm working on trying to split the text of a paragraph using javascript/jQuery to get a specific word. The HTML looks something like this:

<p class="overview">
   Last Name:
   Blah blah blah
   Derp dee derp:
   <br>
   Last Name: Davis
   <br>
   First Name: Jerry     
</p>

I'm trying to extract just the last name (Davis) and save it to a variable, but I cannot figure out how to do it using the javascript .split() method. Right now I'm doing something that I'm sure is so wrong. I don't even want to share it, but here it is.

var splitS = ($("p.overview").text().split(["First Name:", "Last Name:"], 3));

Obviously I do not have a very good grasp on this method and I haven't been able to find anything in my searches that proved to be helpful. Thanks

Edited: Typo ("class="). Also I forgot it's a little more complex than I originally posted. There are more than one occurrence of the string "Last Name:" and there is a break right before and after the last name I'm trying to get out of the p element.

Upvotes: 0

Views: 622

Answers (1)

adeneo
adeneo

Reputation: 318202

Looks like it would be easier with a regex, if the labels (Last Name: etc) are always the same

var txt = $('.overview').text();

var lastName = txt.match(/Last Name: (.*)/)[1];

alert(lastName)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="overview">
   Last Name:
   Blah blah blah
   Derp dee derp:
   <br>
   Last Name: Davis
   <br>
   First Name: Jerry     
</p>

Upvotes: 4

Related Questions