简体   繁体   English

JavaScript toUpperCase 不起作用。 为什么?

[英]JavaScript toUpperCase isn't working. Why?

I am doing a simple function.我正在做一个简单的功能。 To turn all words first-letter to upper case, but It simply doesn't work, neither display any errors:将所有单词首字母大写,但它根本不起作用,也不显示任何错误:

 function formatTitle(input) { var words = input.split(' '); for (var i = 0; i < words.length; i++) { words[i][0] = words[i][0].toUpperCase(); }; return words.join(' '); }; var newTitle = formatTitle("all words first-letter should be upper case"); document.write(newTitle);

Thanks in advance.提前致谢。

The problem is that strings in javascript are immutable.问题是 javascript 中的字符串是不可变的。 You can't just change a char like this.你不能像这样改变一个字符。

A solution would be this:一个解决方案是这样的:

words[i] = words[i][0].toUpperCase()+words[i].slice(1);

But you could have a simpler and faster code using a regular expression:但是您可以使用正则表达式编写更简单、更快的代码:

return input.replace(/\b\w/g,function(b){ return b.toUpperCase() })

(here with a more complete uppercasing, not just after spaces - if you want to stick to spaces use replace(/(\\s+|^)\\w/g,function(b){ return b.toUpperCase() }) ) (这里有一个更完整的大写,而不仅仅是在空格之后 - 如果你想坚持空格使用replace(/(\\s+|^)\\w/g,function(b){ return b.toUpperCase() })

Problem问题

Because因为

words[i][0] = 'something'

does not update the words[i] .不更新words[i]

Problem Demo问题演示

 var myVar = 'abc'; myVar[0] = 'd'; document.write(myVar); // abc

Solution解决方案

You can use substr to get the first character and update the value of whole string.您可以使用substr获取第一个字符并更新整个字符串的值。

Solution Demo解决方案演示

 function formatTitle(input) { var words = input.split(' '); for (var i = 0; i < words.length; i++) { words[i] = words[i].substr(0, 1).toUpperCase() + words[i].substr(1); } return words.join(' '); } var newTitle = formatTitle("all words first-letter should be upper case"); document.write(newTitle);

How wrote Denis the reason is that strings in javascript are immutable (numbers and booleans are also immutable). Denis 怎么写的原因是 javascript 中的字符串是不可变的(数字和布尔值也是不可变的)。

Another very simple solution for Upperize the first char of a string is:将字符串的第一个字符上移的另一个非常简单的解决方案是:

function firstUpper(word) {
     return word.charAt(0).toUpperCase() + word.substring(1);
};

I suggest also to read this post: Understanding Javascript immutable variable我还建议阅读这篇文章: Understanding Javascript immutable variable

Hope this help希望这有帮助

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

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