简体   繁体   中英

Alter text to camel case with loop and function javascript

I'm trying to alter text to camel case with a function. The hyphen in text indicates where the letters need to be capitalized. ie "this-has-been-camel-cased" would become thisHasBeenCamelCased . I've altered each word and am wanting to return them as a concatenated string using += .However when I try to return the string the += is not recognised or I get an error message stating "fullWord not defined". This is odd as the var fullWord is recognised when I alert it inside the loop ?

Where is the error coming from here. how can I correct it ?

Thaks

function camelize(str) {
    var wordArr = str.split('-');
    for (var i = 0; i < wordArr.length; i++) {
        var ltrArr = wordArr[i].split('');
        var firstLtr = ltrArr[0].toUpperCase();
        var endWord = ltrArr.slice(1).join('');
        var fullWord = firstLtr.concat(endWord);
        var newStr += fullword;
    }
    return newStr;
}

alert(camelize('this-has-been-camel-cased')); 

Simpler alternative :

'this-has-been-camel-cased'.replace(/-./g, function (m) {
    return m[1].toUpperCase();
});

Here is a function :

function camelize(input, splitter) {
    if (!splitter) splitter = '-';
    return input.replace(new RegExp(splitter + '.', 'g'), function (m) {
        return m[1].toUpperCase();
    });
}

And a "no regular expression" version :

function camelize(input, splitter) {
    var i = 0;
    if (!splitter) splitter = '-';
    input = input.split(splitter);
    while (++i < input.length) {
        input[i] = input[i].charAt(0).toUpperCase() + input[i].slice(1);
    }
    return input.join('');
}

Usage examples :

camelize('az-er-ty') // "azErTy"
camelize('az er ty', ' ') // "azErTy"

Problems I detect on your code at first sight:

  • This code var newStr += fullword; is invalid. You cannot use += when declaring a variable

  • You have to use fullWord and not fullword (notice the casing problem with w

  • You need to declare (at least) newStr outside of the for loop, otherwise it will be initialized on every iteration.

var newStr += fullword; is redeclared within the loop, declare it outside with an initial value.

alternative;

str = str.replace(/-(.)/g, function($1) { return $1.toUpperCase(); }).replace(/-/g, '');

The problem is indeed with += .

It results from the fact that the purpose of += is to add a string or number to another, but in this case you are using it on a variable that does not yet have anything assigned to it: newStr can't have any strings added to it, since it doesn't exist at the time you're invoking it.

What you need is a direct assignment:

var newStr = fullword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM