Reputation: 11951
How can I remove the second
occurrence of the decimal number $275.75 in the received subTotal using regex and include $
in the regex ? But now I am getting NaN as output.
Expected output:
Here is the result: $275.75
let subTotal = "\n \n Sub-Total \n \r \r $275.75 \n\n $275.75";
let myTotal = Number(subTotal.replace(/\n|\r|[^0-9\.]+/g, ""));
console.log("Here is the result: "+myTotal);
Upvotes: 0
Views: 338
Reputation: 63524
Instead of doing a replace (since you're not using the string in your output) match
might be a better alternative. Just grab the first match
with /\$[0-9\.]+/
.
let subTotal = "\n \n Sub-Total \n \r \r $275.75 \n\n $275.75";
let myTotal = subTotal.match(/\$[0-9\.]+/);
console.log(`Here is the result: ${myTotal}`);
Upvotes: 1
Reputation: 25408
You can use
\b\d+\.\d+\b
and get all numbers with a decimal point in an array and get the specific element using array index
let subTotal = "\n \n Sub-Total \n \r \r $275.75 \n\n $275.75";
let myTotal = subTotal.match(/\b\d+\.\d+\b/g);
console.log(myTotal);
console.log(`Here is the result: $${myTotal[0]}`);
or
\$\b\d+\.\d+\b/g
let subTotal = "\n \n Sub-Total \n \r \r $275.75 \n\n $275.75";
let myTotal = subTotal.match(/\$\b\d+\.\d+\b/g);
console.log(myTotal);
console.log("Here is the result: " + myTotal[0]);
Upvotes: 2
Reputation: 9041
This doesn’t use regex, but it still returns what you want. This is the example code from this site. It uses Number.prototype.toFixed
function financial(x) {
return Number.parseFloat(x).toFixed(2);
}
console.log(financial(123.456));
// expected output: "123.46"
console.log(financial(0.004));
// expected output: "0.00"
console.log(financial('1.23e+5'));
// expected output: "123000.00"
What you may want
let myTotal = financial(subTotal.match(/[\d+\.]/)[0])
console.log("Here is the result: $"+myTotal);
Upvotes: 0