简体   繁体   English

Javascript正则表达式可从字符串开头删除数字以外的任何内容

[英]Javascript regex to remove anything but numbers from the start of a string

I have some strings like this: 我有一些像这样的字符串:

var st1 = 'AU$99.95'; // Should return 99.95 //应该返回99.95

var st2 = 'AU.99.95'; // Should return 99.95 //应该返回99.95

var st1 = 'Blahblah $99,000'; // Should return 99,000 //应该返回99,000

My current regex gets me most of the way there, I'm just using string.replace(/[^0-9.,]/g, ""); 我当前的正则表达式使我获得了大部分帮助,我只是在使用string.replace(/[^0-9.,]/g, ""); .

This works for all scenarios except for #2, when there is an allowed character that is before a number. 当#2之前的数字允许有字符时,此方法适用于除#2以外的所有方案。 I want to ONLY allow . 我只允许. and , when there is a number preceding it. ,如果前面有数字。 How can I achieve this? 我该如何实现?

(I know I can write a javascript function to do this, but I'd rather take care of it all in the one regex replace) (我知道我可以编写一个javascript函数来做到这一点,但我宁愿在一个regex替换中解决所有问题)

EDIT: 编辑:

Apologies, small oversight. 道歉,小疏忽。 I also need to remove any text after the number (I assumed before/after numbers wouldn't make a difference, but apparently they do!). 我还需要删除数字之后的所有文本(我假设数字之前/之后不会有什么不同,但显然它们可以!)。 So: 所以:

var st4 = 'blahblah $.99,000AUD // should return 99,000 var st4 = 'blahblah $.99,000AUD //应该返回99,000

也许

string.replace(/^[^0-9]*/, "");

你可以这样做

str.replace(/^[^\d]*/,"").replace(/[^\d]*$/,"");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM