简体   繁体   中英

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,00- -> 50,00
  • -5-0,- -> -50,-

Edit: double minus at the end or start should also be stripped.

  • --50,00 -> -50,00
  • 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.

RegExp Boundaries

\\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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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