我有这个问题。我只想删除字符串中的最后一个数字,比如"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我该如何解决这个问题呢?
发布于 2019-12-18 12:00:11
如果只想删除出现在末尾的数字,可以在现有表达式后使用表达式末尾锚定字符$:
// 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, ''));
发布于 2019-12-18 12:00:25
var aa = /\d+$/
var s = "tai-xe-bang-bk2k8398"
s.replace(aa,"")https://stackoverflow.com/questions/59385276
复制相似问题