Javascript 将字符串替换为特定的规律的字符串

时间:2022-01-21 13:42:24

Javascript 将字符串替换为特定的规律的字符串

这是测试过程,可以再简化一点。


function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  
  console.log('把下划线转成空格');
  str = str.replace(/\_/g, ' ');
  console.log(str);
  
  console.log('把多个空白符转成一个空格');
  str = str.replace(/\s+/g, ' ');
  console.log(str);
  
  console.log('在大写前面加上一个空格');
  str = str.replace(/([A-Z])/g, ' $1');
  console.log(str);
  
  console.log('去除字符串首字空白');
  str = str.replace(/^\s/g, '');
  console.log(str);
  
  console.log('将空白符替换为 -');
  str = str.replace(/\s+/g, '-');
  console.log(str);

  
  console.log('转成小写');
  str = str.toLowerCase();
  console.log(str);
  return str;
}


spinalCase('This Is Spinal Tap');