[英]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.