[英]How can I add regex for this one?
我想在“理发”和“洗发”之间添加逗号,基本上是这样的:“ Haircut, Wash And Blow Dry
if(string === 'HaircutWashAndBlowDry'){
string.charAt(0).toUpperCase() + string.slice(1);
str = str.replace(/([A-Z])/g, ' $1').trim();
}
您不需要小写首字母。 结合使用\\B
和一个简单的计数器:
var str = 'HaircutWashAndBlowDry'; var i = 1; console.log(str.replace(/\\B([AZ])/g, function(match, $1) { return ( i++ == 1 ? ', ' : ' ' ) + $1; }))
有趣的目标:)让我们玩一些先前的答案(testCase 2和testCase 3),它们依赖于单词的位置,更广泛的方法依赖于And
字符串的拆分以表现出不同的行为:
// Haircut, Wash And Blow Dry let strings = [ 'HaircutWashAndBlowDry', 'HaircutWashCleanAndBlowDrySet' ]; function testCase1(str) { let pieces = str.split('And'); pieces[0] = pieces[0].replace(/([az])([AZ])/g, '$1, $2'); pieces[1] = pieces[1].replace(/([az])([AZ])/g, '$1 $2'); return pieces[0] + ' And ' + pieces[1]; } function testCase2(string) { return string.replace(/^([AZ][^AZ]*)([AZ])|([AZ])/g, function($0,$1,$2,$3) {return $2 ? $1 + ", " + $2 : " " + $3 ;}); } function testCase3(str) { let i = 1; return str.replace(/\\B([AZ])/g, function(match, $1) { return ( i++ == 1 ? ', ' : ' ' ) + $1; }); } strings.forEach(str => { console.log(str); console.log('testCase1 : ' + testCase1(str)); console.log('testCase2 : ' + testCase2(str)); console.log('testCase3 : ' + testCase3(str)); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.