javascript - Remove every character from a string except the numbers and characters between them
问题描述
The problem I'm facing is that I'm unable to get number from a string along with dot or comma between those numbers.
Example string: 'kr.2.000,00 DKK' OR '$150.65 USD' OR '€340.00 EUR'
From this string I need to fetch '2.000,00' using regex. so basically the regex would be to fetch numbers and any character that is between them and store them in a variable.
This is my code:
var oldPrice = 'kr.2.000,00 DKK';
var newPrice = oldPrice.replace(/^\d+(\.|,)?\d+(\.|,)?\d+$/igm, "");
I need 2.00,00 in variable newPrice. Please help guys!
解决方案
您的模式在正确的轨道上,您只需要删除^
和$
锚点即可使其工作。然后,在您的输入字符串上重复应用它以提取您想要的值。请注意,我对模式所做的一项更改是允许初始数字之后的分隔符/数字部分重复任意次数。这涵盖了一个输入,例如1,500,000
,它有超过一千个分隔符。
var re = /\d+(?:[,.]?\d+)*[,.]?\d+/g;
var input = "kr.2.000,00 DKK' OR '$150.65 USD' OR '€340.00 EUR OR ¥1,500,000";
var m;
do {
m = re.exec(input);
if (m) {
console.log(m[0]);
}
} while (m);
推荐阅读
- ios - 登录后如何显示用户的名字?
- linux - 为什么proc_read()是Linux中与/proc相关的函数,被“反复”调用,直到返回0?
- javascript - 尽管重新启动浏览器,ember-simple-auth 用户仍保持登录状态
- reactjs - VSCode - 更新文件名更改的导入路径?
- javascript - Vuetify - 观察 v-app-bar 的变化,例如 onScroll()
- apache-kafka - RocksDBException - Kafka 消费者没有可用的锁
- reactjs - 如何在chartjs中的多系列饼图中显示名称
- powershell - Powershell Remove-Item 与 cmd rd /s /q "path"
- magento2 - Magento 2 - 本地环境配置
- html - 搜索项的 flex 错误