JS Regex删除字符串中最后一个连字符后的数字



尝试删除最后一个连字符后的数字。我试过下面的,但没有成功。

const str = 'HYC-HTY-VB23';
const result = str.toLowerCase().replace(/-d*$/, "");
console.log('result = ', result);

如果我将其更改为-w,它将删除最后一个连字符后的所有值,但我只希望删除最后一次连字符后。在regex中,任何人都对此有任何想法。

谢谢,

这将适用于的所有可能方式

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);

您可以捕获连字符之后但字符串末尾之前的前导字符,然后替换为这些字符:

const str = 'HYC-HTY-VB23';
const result = str.toLowerCase().replace(/(-.*?)d*$/, "$1");
console.log('result = ', result);

如果前导部分没有任何数字,只有字母(例如,不可能以-12VB23结尾),那么(-[a-z]*)d*$就可以了。

连字符逻辑可能也没有必要——除非希望从带连字符的输入中删除数字(并保留其他以数字结尾的输入),否则可以.replace(/d+$/, '')

另一个选项是使用一个匹配1个或多个数字的单个替换来断言除右侧的-之外的任何字符,直到使用正向前瞻(?=[^-]*$)的字符串结束

d+(?=[^-]*$)

Regex演示

const str = 'HYC-HTY-VB23';
const result = str.toLowerCase().replace(/d+(?=[^-]*$)/, "");
console.log('result = ', result);


如果必须存在连字符,您也可以使用

(?<=-[^-]*)d+(?=[^-]*$)

Regex演示

使用

const str = 'HYC-HTY-VB23';
const result = str.toLowerCase().replace(/(?<=-[^-]*)d(?=[^-]*$)/g, "");
console.log('result =', result);

结果result = hyc-hty-vb

解释

--------------------------------------------------------------------------------
(?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
-                        '-'
--------------------------------------------------------------------------------
[^-]*                    any character except: '-' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
)                        end of look-behind
--------------------------------------------------------------------------------
d                       digits (0-9)
--------------------------------------------------------------------------------
(?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
[^-]*                    any character except: '-' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
$                        before an optional n, and the end of
the string
--------------------------------------------------------------------------------
)                        end of look-ahead

相关内容

最新更新