试图在最后一个连字符之后删除数字。我试了下,但没有工作。
const str = 'HYC-HTY-VB23';
const result = str.toLowerCase().replace(/-\d*$/, "");
console.log('result = ', result);如果我将其更改为\w,它将删除最后一个连字符之后的所有值,但我只希望删除最后一个连字符之后的数字。任何人在这方面都有任何想法。
谢谢,
发布于 2021-01-17 04:16:12
这将适用于所有可能的方法。
HYC-HTY-VB23 -> hyc-hty-vb✓
HYC-HTY-23VB -> hyc-hty-vb✓
HYC-HTY-2V3B -> hyc-hty-vb✓
HYC-HTY-2VB3 -> hyc-hty-vb✓
const str = 'HYC-HTY-2V3B'; // Even for this
const result = str.toLowerCase().replace(/[^-]+$/, (textAfterHypen) => {
const withoutNumber = textAfterHypen.replace(/\d/g, "");
return withoutNumber;
});
console.log('result =', result);
一衬垫
const str = 'HYC-HTY-2V3B';
const result = str.toLowerCase().replace(/[^-]+$/, t => t.replace(/\d/g, ""));
console.log('result =', result);
发布于 2021-01-17 04:10:27
您可以捕获在连字符之后但在字符串结束之前的前导字符,然后用以下字符替换:
const str = 'HYC-HTY-VB23';
const result = str.toLowerCase().replace(/(-.*?)\d*$/, "$1");
console.log('result = ', result);
如果前面的部分没有任何数字,那么只有字母(例如,以-12VB23结尾是不可能的),(-[a-z]*)\d*$才能工作。
连字符逻辑也可能没有必要--除非您只想从带有连字符的输入中删除数字(并保留其他以数字结尾的输入),否则可以.replace(/\d+$/, '')。
https://stackoverflow.com/questions/65757231
复制相似问题