簡體   English   中英

如何對美元符號和逗號使用替換方法?

[英]How to use replace method for dollar sign and comma?

我想完成兩件事,將余額解析為整數(我假設這是需要的),然后使用 reduce 方法將總余額相加。 我不知道刪除逗號的最佳方法是什么? 還是我應該改用拼接? 如果 reduce 方法現在添加它們,它只會添加逗號前的第一個數字,即 1,1,8。

const data = [{
    index: "14",
    name: "Bob",
    balance: "$1,000",
  },
  {
    index: "23",
    name: "John",
    balance: "$1,200",
  },
  {
    index: "17",
    name: "Steve",
    balance: "$8,000",
  },
];
const balances = data.map((amount) => {
  var newAmount = parseFloat(amount.balance.replace(/\$/g, ""));
  return newAmount;
});

console.log(balances);

const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(balances.reduce(reducer));

這將嘗試刪除 $ 並將余額相加並顯示出來。 但是我不知道如何刪除逗號(應該修復它)?

使用替換

 const data = [ { index: "14", name: "Bob", balance: "$1,000", }, { index: "23", name: "John", balance: "$1,200", }, { index: "17", name: "Steve", balance: "$8,000", }, ]; const result = data.map((o) => parseFloat(o.balance.replace(/[$,]/g, ""))).reduce((acc, curr) => acc + curr, 0); console.log(result);

使用匹配

 const data = [{ index: "14", name: "Bob", balance: "$1,000", }, { index: "23", name: "John", balance: "$1,200", }, { index: "17", name: "Steve", balance: "$8,000", }, ]; const result = data.map((o) => { return +o.balance.match(/[\d]+/g).join(""); }).reduce((acc, curr) => acc + curr, 0); console.log(result);

或者

 const data = [ { index: "14", name: "Bob", balance: "$1,000", }, { index: "23", name: "John", balance: "$1,200", }, { index: "17", name: "Steve", balance: "$8,000", }, ]; const result = data.map((o) => parseFloat(o.balance.match(/[\d]+/g).join(""))).reduce((acc, curr) => acc + curr, 0); console.log(result);

您可以使用character class [$,]接受方括號內的任何字符。

 const getAmount = (amount) => { return parseFloat(amount.replace(/[$,]/g, "")); } console.log(getAmount("$123,45.132"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM