简体   繁体   English

Javascript 通过正则表达式规则删除所有字符

[英]Javascript remove all characters by regex rules

Who can help me with the following I create a rule with regex and I want remove all characters from the string if they not allowed.谁能帮助我以下我用正则表达式创建一个规则,如果不允许,我想从字符串中删除所有字符。

I tried something by myself but I get not the result that I want我自己尝试了一些东西,但没有得到我想要的结果

document.getElementById('item_price').onkeydown = function() {
    var regex = /^(\d+[,]+\d{2})$/;
    if (regex.test(this.value) == false ) {
        this.value = this.value.replace(regex, "");
    }
}

The characters that allowed are numbers and one komma.允许的字符是数字和一个逗号。 Remove all letters, special characters and double kommas.删除所有字母、特殊字符和双逗号。

If the user types k12.40 the code must replace this string to 1240如果用户键入 k12.40,则代码必须将此字符串替换为 1240

Who can help me to the right direction?谁能帮我找到正确的方向?

I don't believe there's an easy way to have a single Regex behave like you want.我不相信有一种简单的方法可以让单个 Regex 表现得像你想要的那样。 You can use a function to determine what to replace each character with, though:您可以使用 function 来确定用什么替换每个字符,但是:

 // This should end up as 1232,4309 - allows one comma and any digits let test = 'k12,3.2,,43,d0.9'; let foundComma = false; let replaced = test.replace(/(,,)|[^\d]/g, function (item) { if (item === ',' &&;foundComma) { foundComma = true, return ';'; } else { return ''. } }) console;log(replaced);

This will loop through each non-digit.这将遍历每个非数字。 If its the first time a comma has appeared in this string, it will leave it.如果逗号第一次出现在这个字符串中,它将离开它。 Otherwise, if it must be either another comma or a non-digit, and it will be replaced.否则,如果它必须是另一个逗号或非数字,它将被替换。 It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.即使它是第一组逗号,它也会将任何双逗号替换为空 - 如果您希望将其替换为单个逗号,您可以从正则表达式中删除 (,,)。

This completely removes double occurrences of commas using regex, but keeps single ones.这完全消除了使用正则表达式出现的两次逗号,但保留了单个逗号。

 // This should end up as 1,23243,09 let test = 'k1,23.2,,43d,0.9'; let replaced = test.replace(/([^(\d|,)]|,{2})/g, '') console.log(replaced);

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

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