Reputation:
So this is my code:
function PlusMinus() {
str = str.replace(/([^\d\.](?!.*[^\d\.]))/, function(m, $1) {
if ($1 == "-") return "";
return $1 + "-";
});
}
And it isn't working.
What I want to do, is to find the last occurrence of any character that is not a number (0-9) or a dot (.) and then if it is a "-", remove it, if it isn't replace the char with the char + "-".
Simply like a calculators -/+ button.
Examples:
"" -> "-"
"-" -> ""
"abc2-3" -> "abc23"
"a2-" -> "a2"
"s23.3" -> "s-23.3"
"4f" -> "4f-"
And yes, I've seen this: JavaScript RegExp: Can I get the last matched index or search backwards/RightToLeft? but I can't get it to work for chars in brackets
Upvotes: 0
Views: 133
Reputation: 324810
I would say something like this:
str.replace(/(?:^|.)(?=[\d.]*$)/,function(c) {
return c == "-" ? "" : c+"-";
});
This will find a character such that all the characters after it are either numbers or a dot. Due to the greedy nature of quantifiers and the left-to-right processing of regexes, this will be the first such character found, which will be the last non-digit, non-dot character.
However, be sure to return
or otherwise do something with the result! Otherwise you're just discarding it.
Upvotes: 1
Reputation: 43728
plusMinus(''); //'-'
plusMinus('-'); //''
plusMinus('abc2-3'); //'abc23'
plusMinus('a2-'); //'a2'
plusMinus('s23.3'); //s-23.3
function plusMinus(str) {
return str.replace(/(^|[^\d\.])(?=[\d\.]*$)/, function ($0) {
return $0 === '-'? '' : $0 + '-';
});
}
I am just unsure about what to do with something like 33
, because now it will return -33
. Is this the desired behavior?
Upvotes: 0