如何为此添加正则表达式?

时间:2018-05-25 20:26:53

标签: javascript regex

我想在Haircut和Wash之间添加逗号。基本上是这样的:Haircut, Wash And Blow Dry

 if(string === 'HaircutWashAndBlowDry'){
    string.charAt(0).toUpperCase() + string.slice(1);
    str = str.replace(/([A-Z])/g, ' $1').trim();
  }

2 个答案:

答案 0 :(得分:1)

您不需要小写第一个字母。使用\B和一个简单的计数器:



var str = 'HaircutWashAndBlowDry';
var i = 1;
console.log(str.replace(/\B([A-Z])/g, function(match, $1) {
    return ( i++ == 1 ? ', ' : ' ' ) + $1; 
}))




答案 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(/([a-z])([A-Z])/g, '$1, $2');
  pieces[1] = pieces[1].replace(/([a-z])([A-Z])/g, '$1 $2');
  return pieces[0] + ' And ' + pieces[1];
}

function testCase2(string) {
  return string.replace(/^([A-Z][^A-Z]*)([A-Z])|([A-Z])/g, function($0,$1,$2,$3) {return $2 ? $1 + ", " + $2 : " " + $3 ;});
}

function testCase3(str) {
  let i = 1;
  return str.replace(/\B([A-Z])/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));
});