首页 > js字符串的操作问题

js字符串的操作问题

将 var str = 'this-is-str';将'-'后的字母大写,即修改为thisIsStr的最简单方法是什么呢.

补充一下自己写的代码,感觉写的比较繁琐.

a = a.replace(a[0] , a[0].toUpperCase());
for(var i in a ){
    if(a[i] === '-'){
        a = a.replace(a[i] + a[parseInt(i) + 1] , a[parseInt(i) + 1].toUpperCase());
    }
}

而且有一个疑问,为什么

typeof(i) == String;

根据楼下的代码,自己写成了reduce的形式,感觉其实没什么区别:

var a = "this-is-st".split('-');
a = a.reduce(function(pre,next){
    pre += next.charAt(0).toUpperCase() + next.substr(1);
    return pre;
},'');

var str = 'this-is-str';
var r = /(-)(\w)/g;
str = str.replace(/(-)(\w)/g,function(match,p1,p2){
    return p2.toUpperCase();
});

不用正则的话,可以这么做。核心思想还是先分组然后reduce。

function camelCase(string, separator) {
  const capitalize = str => {
    const lower = str.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };

  return string.split(separator).reduce((result, item, index) => {
    const lowerCase = item.toLowerCase();
    return result + (index ? capitalize(lowerCase) : lowerCase);
  }, '');
}
typeof(i) == String;

关于这个问题,其实没什么好说的,Arrayindex本身就是一个String,跟你遍历的是不是String对象没有关系。之所以arr[1]能用,是系统自动帮你转换成String了。

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4


感觉自己的也不是很简洁,不过可以通过正则表达式来实现。

    var a = "this-is-st".split('-');
    for(var i=1;i<a.length;i++){
      a[i] = a[i].charAt(0).toUpperCase()+a[i].substr(1);
    }
   typeof(i) == String; 
   

是由于你遍历的是一个字符串这里说法错误,经过在chrome console中验证的确与类型无关。

    var arr = {a:1,b:[1]}
    for(var i in arr){
      console.log(typeof i);     //输出两次string
    }
【热门文章】
【热门文章】