0

I have a string like this:

string="Awesome Option +$399.99";

I want to remove the +$399.99 (and any other pricing details) from the string, how would you do that?

Oh and the string could also possibly look like this:

string="#4 Cool Option +$23.99"

Talon
  • 4,937
  • 10
  • 43
  • 57

3 Answers3

4
var text = 'Awesome Option +$399.99';
text = text.substring(0, text.indexOf('+$'));
// text is "Awesome Option "
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • I like that you've avoided regular expressions, but this would truncate strings such as `Awesome Option +$399.99 More text +$5.99`. – Jason McCreary Sep 22 '11 at 20:44
  • @Jason your point isn't invalid, per se, but handling such strings wasn't specified as a requirement in the OP. – Matt Ball Sep 22 '11 at 21:00
  • Possibly implied: *I want to remove the +$399.99 (**and any other pricing details**) from the string*. Regardless, good answer +1. – Jason McCreary Sep 22 '11 at 22:27
3

You would do: string.replace(/\s*\+\$.*$/, ''). Note that this does not depend on jQuery.

This also removes white space in front of the +$. If the + is optionally there, you'd use string.replace(/\s*\+?\$.*$/, '').

Augustus Kling
  • 3,303
  • 1
  • 22
  • 25
3
var originalString = "Awesome Option +$399.99"
var truncatedString = originalString.split("+")[0]

Using the same logic you could extract just the price this way, or both at the same time.

David
  • 844
  • 6
  • 14