gpt4 book ai didi

javascript - 我如何才能只删除文本中的最后一个数字

转载 作者:行者123 更新时间:2023-11-30 09:10:37 24 4
gpt4 key购买 nike

我有这个问题。我只想删除字符串中的最后一个数字,如“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com