为什么不将小写应用于以下替换链中的每个单词

Why isn't toLowerCase being applied to every word in the following replace chain?

本文关键字:单词 替换 应用于 为什么不      更新时间:2023-09-26

我想把这个:livingRoom变成这个Living room

因此,作为第一步,我想打破骆驼大小写单词并将每个单词转换为小写:

"livingRoom"
  .replace(/([A-Z])/g, ' $1')
  .replace(/^./, function(str){ return str.toLowerCase(); })

但是,我得到这个:

// => "living Room"

可能是什么原因?

你可以试试:

"livingRoom"
  .replace(/([A-Z])/g, function(str){ return ' '+ str.toLowerCase(); })
  .replace(/^.?/, function(str){ return str.toUpperCase(); })
//"Living room"

/^./只匹配第一个字符"l",它已经是小写的。

console.log("livingRoom"
  .replace(/([A-Z])/g, ' $1')
  .replace(/ [A-Z]/, function(str){ return str.toLowerCase(); })
  .replace(/^./, function(str){ return str.toUpperCase(); }));

^. 只是替换第一个字符

你有,

// This replace 'R' in 'livingRoom' with space + group1, which is ' R'.
.replace(/([A-Z])/g, ' $1') // Returns 'living Room'
// This finds any character after the beginning of line. which is 'l'.
.replace(/^./, function (str) { return str.toLowerCase() }); // str is 'l'

但是,例如,还有另一种简单的方法可以接近"客厅"。

var str = "livingRoom"
    .replace(/([A-Z])/g, ' $1');
// str is now 'living Room'
// Uppercase the first char in str, and concat it with the lowercased rest.
str = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
// str is now 'Living room'