简体   繁体   English

将String转换为大写和小写

[英]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'. 给出的错误状态为“未捕获”和“ TypeError:未定义不是函数”。 I know my problem is line 11 and 12 with the toUpperCase() and toLowerCase() methods but I don't know why. 我知道我的问题是使用toUpperCase()和toLowerCase()方法的第11行和第12行,但是我不知道为什么。

The current error you're getting is because your firstName variable contains an Array and not a String. 您当前遇到的错误是因为firstName变量包含一个Array而不是一个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. 但是,您应该添加一些检查,而不仅仅是假设传入的名称也将采用“单词单词”格式。

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. 即使在其上调用pop()之后, splitNames仍然是一个数组,如果将其分配给firstName ,则firstName将是同一数组,没有toLowerCase()方法。

Try: 尝试:

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

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

When you assign splitNames to firstName, you are assigning an array to firstName, and arrays don't have a lowercase or uppercase method. splitNames分配给firstName时,就是将数组分配给firstName,并且数组没有小写或大写方法。

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: 另外,如果您已经声明了变量,则无需重复使用var,而忘记在倒数第二行中将新名称添加在一起:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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