-4

I have $45.00 as string and need to get 45 out of that. following is working... How do I write this in one line?

var x= "$45.00" ,cents =/\.00$/;
var z= x.replace(/^\$/,'');
z = z.replace(cents,'');
1234
  • 241
  • 1
  • 3
  • 15

2 Answers2

0

Basically, the .replace() calls can be daisy-chained, with the second one acting on the results of the first:

var x = "$45.00", cents = /\.00$/, z = x.replace(/^\$/, '').replace(cents, '');
Chad
  • 693
  • 5
  • 17
  • 4
    While this is essentially what the OP asked for, this one line of code is much harder to read than the original 3 lines. – Tot Zam Nov 23 '15 at 01:24
  • var x= "$45.05" ,doller =/^\$/, cents =/\.00$/; var z= x.replace(doller,'').replace(cents,''); works fine and clean – 1234 Nov 23 '15 at 02:37
0

If the question is that straight forward you can simply use this one line to get the left of the dot value.

var x= "$45.00".split('$')[1].split('.')[0];

Explanation:

  1. You assign the variable x to the price string in this case "$45.00"
  2. Then use the string function split, to divide the string into two arrays.
  3. Right now you have ["$"] in position zero and the rest in position 1 ["45.00"]
  4. You then use the same function on the second array at position one to divide at the dot character.
  5. Now you have at position zero ["45"] and position 1 [".00"]
  6. You need position 0 so that's the index you you will use and that's it.

I think it's pretty straightforward but tried to be as through as possible.

Mazen Elkashef
  • 3,430
  • 6
  • 44
  • 72