用小写字母和连字符替换整个字符串中的大写字母

Wil*_*997 1 javascript regex string replace

我试图用小写的计数器部分替换整个字符串中的大写字母,同时在它后面添加连字符(除非是最后一个字母)。所以那Sunny&Cloudy会来sunny-&-cloudy

var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');
Run Code Online (Sandbox Code Playgroud)

我自己试过这个,但它只到达第一个大写字母添加一个连字符并停止。留下我-S

小智 5

如果你想转换Sunny&Cloudysunny-&-cloudy,那么下面的代码应该可以工作:

var name = 'Sunny&Cloudy';
name.replace(/[A-Z][a-z]*/g, str => '-' + str.toLowerCase() + '-')
  // Convert words to lower case and add hyphens around it (for stuff like "&")
  .replace('--', '-') // remove double hyphens
  .replace(/(^-)|(-$)/g, ''); // remove hyphens at the beginning and the end
Run Code Online (Sandbox Code Playgroud)

基本上,您只需使用 afunction作为 的第二个参数.replace。(参考

它不仅用小写字母替换大写字母,因此您可能需要修改您的问题描述。