如何在jquery中只删除字符中的最后一个点?
示例:
1..
1.2.
预期结果:
1
1.2
我的代码:
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))
我该如何解决这个问题?感谢
您可以使用regex替换:
function removeLastDot(value) {
return value.replace(/.*$/, '')
}
console.log(removeLastDot('1..'))
console.log(removeLastDot('1.2.'))
在示例中,我使用.*$
regex:
$
-表示我希望在字符串末尾进行替换.*
-意味着我想为.
符号匹配任何数字(由于.
是正则表达式中的特殊符号,所以它被转义(
您可以使用forEach遍历字符串,并将任何数字的最后一个索引存储在变量中。然后切片到那个变量。
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));
这将是一个最佳解决方案。
也许这会有所帮助。
var t = "1...";
while (t.substr(t.length - 1, 1) == ".") {
t = t.substr(0,t.length - 1);
}
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
添加replace(/.*$/g, '')
以匹配字符串末尾的一个或多个点。
所以你的代码应该是这样的:
var maskedNumberValue = $(maskedNumber).val().replace(/[^0-9.]/g, '').replace('.', 'x').replace('x', '.').replace(/[^d.-]/g, '').replace(/.*$/g, '');