在 Javascript 中使用 for 循环创建一个驼峰大小写函数



我是Javascript的新手,并试图弄清楚如何使用for循环来区分任何字符串。这就是我目前所拥有的。

function camelCase(str) {
 var splitStr = "";
 var result = "";
 splitStr = str.split(" ");
 for(var i = 0; i < splitStr.length; i++){
 result += splitStr[i][0].toUpperCase() + 
   splitStr[i].slice(1);
  }
  return result;
 }
console.log(camelCase("hello there people"));

它返回"HelloTherePeople" - 我如何使splitStr(splitStr[0][0](的第一个索引从大写中排除,但仍包含在字符串的开头?

你的分隔符是什么?此方法假定下划线_ 。如果需要空格,请将其更改为空格。或者使其成为您可以传递给骆驼化的变量。

if( !String.prototype.camelize )
    String.prototype.camelize = function(){
        return this.replace(/_+(.)?/g, function(match, chr) {
            return chr ? chr.toUpperCase() : '';
        });
    }
"a_new_string".camelize()
//"aNewString"

正则表达式/_+(.)?/g/说找到 1 个或多个_字符,后跟任何字符.(.)创建一个捕获组,因此您可以获得一个字符。它作为第二个参数传递给函数 chr . ?的意思是不贪婪,所以它会在下一个_停止。g意味着全局,几乎意味着找到所有匹配项。

String.prototype.replace参考

资料

更改返回如下:

return result[0].toLowerCase()+result.substr(1);

您可以在循环中检查您是否在第一个索引上。

function camelCase(str) {
  //splitStr will be an array
  var splitStr = [];
  var result = "";
  
  splitStr = str.split(" ");
  
  //Capitalize first letter of words starting from the second one
  for(var i = 0; i < splitStr.length; i++){
  
    //first word
    if (i===0) {
      //Good practice to lowercase the first letter regardless of input
      result += splitStr[i][0].toLowerCase() + splitStr[i].slice(1);
    }
  
    else {
      //rest can proceed as before
      result += splitStr[i][0].toUpperCase() + 
      splitStr[i].slice(1);    
    }
  }
  
  
  return result;
  }
console.log(camelCase("hello there people"));

或者,循环甚至可以从第二个索引开始。但是,在从第二个索引运行循环之前,您必须检查splitStr的长度

最新更新