0

If $("div.receipt").text() returns:

Test Order
<br>123 Test St
<br>Testing, MN
<br>55401

How can I select only the last line of the text returned? I'm trying to isolate the zip code only, but don't know how to do it with anything like .split or .replace since the combination of letters and words before it will be different every time.

fejese
  • 4,601
  • 4
  • 29
  • 36
K Miller
  • 1
  • 1
  • 1
  • 2
    Split it at the line breaks, and take the last element of the resulting array … (you might want to trim the value first, so that you don’t end up with an empty last element, should there be an additional line break at the end.) – CBroe Jan 26 '15 at 23:18
  • Thanks! I got it figured out using .trim() .split() and finally .pop() – K Miller Jan 27 '15 at 00:57

2 Answers2

1

Last index approach

var str = $("div.receipt").text();
var i = str.lastIndexOf("\n");
var lastStr = str.substring(i);

@CBroe split on newline approach

var str = $("div.receipt").text();
var splitStr = str.split("\n");
var lastStr = splitStr[splitStr.length - 1];
0

Follow CBroe's advice. I would take the same approach if you can guarantee the last index of the array will contain the value you seek.

Take a look at .split() Here

These functions do the hard work for you, so use them!

Community
  • 1
  • 1