JCD
JCD

Reputation: 69

Converting String to upper and lower case

I'm developing a program that takes a string, splits it, returns the first string with only the first letter capitalized and returns the second string with all the letters capitalized. The code is below:

var name = "ThEoDORe RoOseVElT";

function nameChanger(oldName) {
    var finalName = oldName;

    var splitNames = finalName.split(" ");

    var secondName = splitNames.pop();
    var firstName = splitNames;

    var secondName2 = secondName.toUpperCase();
    var firstName2 = firstName.toLowerCase();

    var finalName = firstName + " " + secondName;

    return finalName; };

The error given states 'Uncaught' and 'TypeError: undefined is not a function'. I know my problem is line 11 and 12 with the toUpperCase() and toLowerCase() methods but I don't know why.

Upvotes: 1

Views: 101

Answers (4)

felix91
felix91

Reputation: 462

function titleCase(str) {
 return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

Upvotes: 0

Millie Smith
Millie Smith

Reputation: 4604

When you assign splitNames to firstName, you are assigning an array to firstName, and arrays don't have a lowercase or uppercase method.

var firstName = splitNames.pop()

Also, you don't need to reuse var if you've already declared a variable, and you forgot to add the new names together on the second to last line:

finalName = firstName2 + secondName2;

Upvotes: 0

JLRishe
JLRishe

Reputation: 101652

Even after you call pop() on it, splitNames is still an array, and if you assign it to firstName, firstName will be that same array, which doesn't have a toLowerCase() method.

Try:

var secondName = splitNames.pop();
var firstName = splitNames.pop();

var secondName2 = secondName.toUpperCase();
var firstName2 = firstName.toLowerCase();

Upvotes: 0

bvaughn
bvaughn

Reputation: 13487

The current error you're getting is because your firstName variable contains an Array and not a String. You can fix that by changing this

var firstName = splitNames;

...to this:

var firstName = splitNames.pop();

However you should add some checking in place instead of just assuming that incoming names will also be in a "word word" format.

Upvotes: 2

Related Questions