Javascript --- 字符串中字符和数字之间的连字符

Javascript --- Hyphen between a character and a number inside a string

请帮我找到一个javascript函数来将像KX02AB1234这样的字符串转换成KX-02-AB-1234。我想在字母和数字组合在一起时添加连字符..

提前致谢

您可以使用 String#match method to extract digit combination(\d+) or non-digit combination(\D+) to an array and then use Array#join 方法用连字符连接它们。

str.match(/\d+|\D+/g).join('-') 

const str = 'KX02AB1234';

console.log(str.match(/\d+|\D+/g).join('-'))

在 PHP 中,您可以使用环视来查找字母和数字之间的空隙(反之亦然)并用连字符替换该空隙:

$str = 'KX02AB1234';
$str = preg_replace('/(?<=[a-z])(?=\d)|(?<=\d)(?=[a-z])/i', '-', $str);
echo $str;

输出:

KX-02-AB-1234

Demo on 3v4l.org