我有这个问题。我只想删除字符串中的最后一个数字,如“tai-xe-lai-xe-bang-b2kh9088”->“tai-xe-lai-xe-bang-b2kh”。我尝试使用正则表达式,但结果是“tai-xe-lai-xe-bang-bkh”这是我的代码
const validateSlug= text => {
const containsNumber =/\d+/
const textArraySplited = text.split('-')
// get final text of array splited
const textSplitedFinal = textArraySplited[textArraySplited.length - 1]
if (containsNumber.test(textSplitedFinal)) {
return text.replace(/\d/g, '')
}
return text
}
const a='tai-xe-bang-bk2k8398'
console.log(validateSlug(a)) //the result is tai-xe-bang-bkk but I want the result is tai-xe-bang-bk2k
我该如何解决这个问题?
最佳答案
如果您只想删除出现在末尾的数字,您可以在现有表达式之后使用表达式结尾 anchor 字符 $
:
// This will only remove consecutive digits that occur at the end
return text.replace(/\d+$/g, '');
例子
const original = 'tai-xe-lai-xe-bang-b2kh9088';
console.log('Original: ' + original);
console.log('Replaced: ' + original.replace(/\d+$/g, ''));
关于javascript - 我如何才能只删除文本中的最后一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59385276/