-2

I looked at several threads but this confused me a little.

How would I extract "Karandeep Singh" from the following string?

<font color="#91D329">Add New Customer: Karandeep Singh</font>

I tried using the replace method because only the name changed, rest of it remains the same, but it gave an error because of the quotes.

Thanks.

  • Can the "Add New Customer" text change? Can the color change? Are you guaranteed " " is always going to be used for the color? Can there be other formatting applied? You need to be way more specific. – djechlin Oct 14 '15 at 20:06
  • Like I stated in the post, only the name changes "Karandeep Singh", everything else remains the same. – Karandeep Singh Oct 14 '15 at 20:09

3 Answers3

2

by using a few methods on the string (substring,indexOf,trim) like this:

s = '<font color="#91D329">Add New Customer: Karandeep Singh</font>';
r = s.substring(s.indexOf(':')+1,s.indexOf('</font>')).trim();
// r is now "Karandeep Singh"
Zo72
  • 14,593
  • 17
  • 71
  • 103
1

You could just use .split(': ')[1] to grab the name.

Also, this thread might help:

get all characters after "," character

Community
  • 1
  • 1
Toiletduck
  • 171
  • 1
  • 13
  • Not if the name has a ":" in it. – djechlin Oct 14 '15 at 20:12
  • Whose name has a ":" in it? :P – Toiletduck Oct 14 '15 at 20:12
  • Someone attempting an HTML injection attack. – djechlin Oct 14 '15 at 20:13
  • That's why you clean your input fields mate. Different subject. – Toiletduck Oct 14 '15 at 20:14
  • This also puts "" in the name. – djechlin Oct 14 '15 at 20:15
  • Gosh you're nitpicky. It wouldn't grab "" if he selected the element by the "" handle. Except no one here know's how he's selecting it so obviously that's not the problem he's trying to solve. – Toiletduck Oct 14 '15 at 20:21
  • yeah idk if my name not ending is "" is really "nitpicky". This question doesn't have anything to do with selecting elements, it has to do with "the string" in the post. Where that came from, or why it's always guaranteed to be of the same color, with the same HTML style, or why we can assume that the input is sanitized (which we can't if it's scraping someone else's page for instance), couldn't tell ya. – djechlin Oct 14 '15 at 20:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92312/discussion-between-toiletduck-and-djechlin). – Toiletduck Oct 14 '15 at 20:33
-1

You'd need

s.substring(40, s.length - 7);

modulo off-by-one errors.

djechlin
  • 59,258
  • 35
  • 162
  • 290