[英]regex that replace any chars (except number/, .)
I have a string.我有一个字符串。 I need to parse it, replacing any chars (except numbers ( 0
to 9
), ,
and .
.我需要解析它,替换任何字符(数字( 0
到9
)、 ,
和.
除外)。
How can I do it with javascript?我怎样才能用 javascript 做到这一点?
Tried with :尝试过:
string.replace(/[a-zA-Z]*/, "");
but seems it doesnt works.但似乎它不起作用。 Also, I need ANY chars, not only aZ (also ?, /, white space, and so on, expect, as said, , and .另外,我需要任何字符,不仅是 aZ(还有 ?、/、空格等,如上所述,期望,和.
Use a negated character class使用否定字符类
[^0-9,.]
and put in any character you don't want to be replaced, it will match all the others.并输入您不想替换的任何字符,它将匹配所有其他字符。
See it here on Regexr在 Regexr 上看到它
You can optimize it by adding a quantifier +
, so that it replaces a sequence of those characters at once and not each by each.您可以通过添加量词+
来优化它,以便它一次替换这些字符的序列,而不是逐个替换。
string.replace(/[^0-9,.]+/g, "");
As Felix Kling pointed out, its important to use the global option g
to match on all occurrences of the pattern.正如 Felix Kling 指出的那样,使用全局选项g
来匹配所有出现的模式很重要。
See it here on Regexr在 Regexr 上看到它
string.replace(/[^\d,.]+/g, "");
should do.应该做。
[^\\d.,]
means "any character except digit, comma or period", a negated character class . [^\\d.,]
表示“除数字、逗号或句点之外的任何字符”,一个否定字符类。+
instead of *
or you'll have lots of empty matches replaced with empty strings.使用+
而不是*
否则您将有很多空匹配项被空字符串替换。/g
so all instances are replaced.使用/g
以便替换所有实例。Try to replace all chars except digits and .
尝试替换除数字和.
,
and do the replace globally: ,
并进行全局替换:
string.replace(/[^0-9\,\.]+/g, "");
Try This Below code is prevent alpha key试试这个 下面的代码是防止 alpha 键
onKeypress="return Custom(event,'[0-9]');"
function Custom(e, cPattern) {
var key = [e.keyCode || e.which];
var pattern = new String(cPattern);
var keychar = String.fromCharCode([e.keyCode || e.which]);
var pattern1 = new RegExp(pattern);
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27)) {
return true;
}
else if (pattern1.test(keychar)) {
return true;
}
else {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.