Reputation: 532
I have e scenario like this: I need to build a jQuery function that takes a string as an input and update the string into another string. The input can be one of these:
A="0"
A="0, 5"
(basically can be "0, any_other_digits_different_from_0")A="0, 58"
A="58"
(basically any number that doesn't start with zero)I want the function to updated to:
A="0"
) update A="--"
A="58"
) DO NOTHING, leave it A="58"
A="0, 5"
update to A="5"
A="0, 58"
) update to A="58"
Option four can have more than two digits after "0, ".
It seems like this can be done by regex somehow but I am not being able to put anything together that can make it work. Any help is appreciated.
Upvotes: 0
Views: 130
Reputation: 386868
You could split the string and take the last value. If zero return '--'
.
function getValue(a) {
return (+a.split(', ').pop() || '--').toString();
}
console.log(getValue("0")); // "--"
console.log(getValue("0, 5")); // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58")); // "58"
A proposal with a regular expression searching for last numbers
function getValue(a) {
return (+a.match(/\d+$/) || '--').toString();
}
console.log(getValue("0")); // "--"
console.log(getValue("0, 5")); // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58")); // "58"
Upvotes: 1