简体   繁体   English

JavaScript RegEx:将不在字符串开头或结尾处的所有负号与货币输入匹配

[英]JavaScript RegEx: match all minuses that are not at start or end of string for currency input

For a currency input I want to replace all minus input that is not at the start of the string or, when it is the last character, is not preceded by a comma. 对于货币输入,我想替换所有不在字符串开头的减号输入,或者当它是最后一个字符时不在逗号前面。

In the input event I'm already calling a replace with a simple regex for some other invalid input: 在输入事件中,我已经在调用一些简单的正则表达式来替换其他无效输入:

        input.replace(/[^0-9\.\,\-]/g, '')
             .replace('.', ',');

It would be great if I could extend this regex to also strip the invalid minuses. 如果我可以扩展此正则表达式以去除无效的负号,那将是很好的。

Some examples of desired behavior: 所需行为的一些示例:

  • 50-50 -> 5050 50-50 > 5050
  • 50,00- -> 50,00 50,00- --> 50,00
  • -5-0,- -> -50,- -5-0,- > -50,-

Edit: double minus at the end or start should also be stripped. 编辑:结尾或开始处的双减号也应删除。

  • --50,00 -> -50,00 --50,00 > -50,00
  • 50,-- -> 50,- 50,-- > 50,-

I figured I could start with a positive lookahead -(?=.) , but that still matches the first character. 我认为我可以先使用正向先行-(?=.) ,但仍与第一个字符匹配。

Additionally, I found this post that pretty much does the opposite (minuses are not allowed at start and end), but that would still match the whole string. 另外,我发现这篇文章的反面非常大(开始和结束处不允许有减法),但是仍然可以匹配整个字符串。 Not the sepatate minuses. 不是分开的缺点。

Any help would be appreciated. 任何帮助,将不胜感激。

Is a function ok? 功能可以吗? This should do the trick: 这应该可以解决问题:

function removeMinus(str) {
  var prefix = str.startsWith("-") ? "-" : "";
  var postfix = str.endsWith(",-") ? "-" : "";
  return prefix + str.split("-").join("") + postfix
}

Use the following approach with specific regex pattern: 对特定的正则表达式模式使用以下方法:

 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,--')); 

You could use word boundary \\b to do that. 您可以使用单词边界\\b来做到这一点。

RegExp Boundaries RegExp边界

\\b

Matches a word boundary. 匹配单词边界。 This is the position where a word character is not followed or preceeded by another word-character, such as between a letter and a space... 在此位置,一个单词字符后没有另一个单词字符或在其前面,例如在字母和空格之间。

https://regex101.com/r/YzCiEx/1 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.

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