FannyKaunang
FannyKaunang

Reputation: 91

Remove last dots from characters in jquery

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

Upvotes: 1

Views: 274

Answers (5)

Juan C.
Juan C.

Reputation: 84

Add replace(/\.*$/g, '') to match one or more dots at the end of the string.

So your code would be like this:

var maskedNumberValue = $(maskedNumber).val().replace(/[^0-9.]/g, '').replace('.', 'x').replace('x', '.').replace(/[^\d.-]/g, '').replace(/\.*$/g, '');

Upvotes: 0

LetzerWille
LetzerWille

Reputation: 5658

import re
s = '1.4....'
# reverse the string
rev_s =  s[::-1]
# find the first digit in the reversed string
if first_digit := re.search(r"\d", rev_s):
    first_digit = first_digit.start()
    # cut off extra dots from the start of the reversed string
    s = rev_s[first_digit:]
    # reverse the reversed string back and print the normalized string
    print(s[::-1])

1.4

Upvotes: 0

Rickyxrc
Rickyxrc

Reputation: 76

maybe this can help.

var t = "1...";
    while (t.substr(t.length - 1, 1) == ".") {
      t = t.substr(0,t.length - 1);
    }

Upvotes: 0

Akshit Bansal
Akshit Bansal

Reputation: 145

You can traverse the string with forEach and store the last index of any number in a variable. Then slice up to that variable.

let lastDigitIndex = 0;
for (let i = 0; i < str.length; i++) {
   let c = str[i];
   if (c >= '0' && c <= '9') lastDigitIndex = i;
};
console.log(str.slice(0, lastDigitIndex-1));

This will be an optimal solution.

Upvotes: 0

KiraLT
KiraLT

Reputation: 2607

You can use regex replace for that:

function removeLastDot(value) {
  return value.replace(/\.*$/, '')
}

console.log(removeLastDot('1..'))
console.log(removeLastDot('1.2.'))

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)

Upvotes: 3

Related Questions