How to remove only the last dots in characters in jquery?
Example:
1..
1.2.
Expected result:
1
1.2
My code:
var maskedNumber = $(this).find('input.CategoryData');
var maskedNumberValue = $(maskedNumber).val().replace(/[^0-9.]/g, '').replace('.', 'x').replace('x', '.').replace(/[^d.-]/g, '');
console.log(maskedNumberValue.slice(0, -1))
How do I solve this problem? Thanks
5
Answers
You can use regex replace for that:
In the example I use
.*$
regex:$
– means that I want replace at the end of string.*
– means that I want to match any number for.
symbol (it is escaped cause.
is special symbol in regex)You can traverse the string with forEach and store the last index of any number in a variable. Then slice up to that variable.
This will be an optimal solution.
Add
replace(/.*$/g, '')
to match one or more dots at the end of the string.So your code would be like this:
maybe this can help.