我试图用小写的计数器部分替换整个字符串中的大写字母,同时在它后面添加连字符(除非是最后一个字母)。所以那Sunny&Cloudy
会来sunny-&-cloudy
var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');
我自己试过这个,但它只到达第一个大写字母添加一个连字符并停止。留下我-S
如果你想转换Sunny&Cloudy
成sunny-&-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
基本上,您只需使用 afunction
作为 的第二个参数.replace
。(参考)
它不仅用小写字母替换大写字母,因此您可能需要修改问题描述。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句