[英]JavaScript RegEx: match all minuses that are not at start or end of string for currency input
对于货币输入,我想替换所有不在字符串开头的减号输入,或者当它是最后一个字符时不在逗号前面。
在输入事件中,我已经在调用一些简单的正则表达式来替换其他无效输入:
input.replace(/[^0-9\.\,\-]/g, '')
.replace('.', ',');
如果我可以扩展此正则表达式以去除无效的负号,那将是很好的。
所需行为的一些示例:
50-50
> 5050
50,00-
--> 50,00
-5-0,-
> -50,-
编辑:结尾或开始处的双减号也应删除。
--50,00
> -50,00
50,--
> 50,-
我认为我可以先使用正向先行-(?=.)
,但仍与第一个字符匹配。
另外,我发现这篇文章的反面非常大(开始和结束处不允许有减法),但是仍然可以匹配整个字符串。 不是分开的缺点。
任何帮助,将不胜感激。
功能可以吗? 这应该可以解决问题:
function removeMinus(str) {
var prefix = str.startsWith("-") ? "-" : "";
var postfix = str.endsWith(",-") ? "-" : "";
return prefix + str.split("-").join("") + postfix
}
对特定的正则表达式模式使用以下方法:
var replaceHyphen = function (str) { return str.replace(/(\\d)-|(-)-/g, '$1$2'); }; console.log(replaceHyphen('50-50')); console.log(replaceHyphen('50,00-')); console.log(replaceHyphen('-5-0,-')); console.log(replaceHyphen('--50,00')); console.log(replaceHyphen('50,--'));
您可以使用单词边界\\b
来做到这一点。
\\b
匹配单词边界。 在此位置,一个单词字符后没有另一个单词字符或在其前面,例如在字母和空格之间。
https://regex101.com/r/YzCiEx/1
var regex = /\\b-+\\b/g; console.log("50-50".replace(regex, '')) console.log("50,00".replace(regex, '')) console.log("-5-0,-".replace(regex, '')) console.log("-5------6-".replace(regex, '')) console.log("-6--66-6,-".replace(regex, ''))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.