如果最后一个连字符是数字,JavaScript中有没有办法删除它后面的所有内容?
product-test-grid-2
所以结果只有:
product-test-grid
正在尝试使用此资源:
删除特定字符后的所有内容
您可以使用带有replace的简单正则表达式。
例如。。
/-d+$/
=后面跟有一个或多个数字d+
的短划线,位于$
的末尾
const reLast = /-d+$/;
const test1 = 'product-test-grid-2';
const test2 = 'product-test-grid-nan';
console.log(test1.replace(reLast, ''));
console.log(test2.replace(reLast, ''));
简单JS,不涉及正则表达式
const label = 'product-test-grid-2'.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
console.log(label.join('-'));
// you can encapsulate it into function
function formatLabel(label) {
label = label.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
return label.join('-');
}
// 2 should be removed at the end
console.log(formatLabel('product-test-grid-2'));
// two should be left untouched
console.log(formatLabel('product-test-grid-two'));
'product-test-grid-2'.replace(/(?<=-)d*$/, '')
将保留最后一个连字符。
'product-test-grid-2'.replace(/-d*$/, '')
将删除它。
拆分依据"-&";,检查最后一项是否是数字:如果是,则弹出,并加入"-":
sentence="product-test-grid-2";
words=sentence.split("-");
if(words[words.length-1].match(/^d+$/)) words.pop();
result=words.join("-");
console.log(result);
你可以用regrx
做到这一点,但在我看来,这似乎是过度杀伤
我会做
const str='product-test-grid-2'
const pos=str.lastIndexOf('-')
const res=str.slice(0,pos)
console.log(res)