JavaScript toUpperCase does not work. What for?

I perform a simple function. To translate all words in the first place to uppercase, but it just does not work, does not 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);
Run code

Thanks in advance.

+4
source share
3 answers

The problem is that the lines in javascript are immutable. You cannot just change char as follows.

The solution would be:

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

But you can have simpler and faster code using a regular expression:

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

(here with a more complete uppercase, not just after spaces - if you want to use spaces, use replace(/(\s+|^)\w/g,function(b){ return b.toUpperCase() }))

+9
source

Problem

Because

words[i][0] = 'something'

does not update words[i].

Problem

var myVar = 'abc';

myVar[0] = 'd';

document.write(myVar); // abc
Run code

Decision

substr, .

-

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);
+6

As Denis wrote, the reason is that the lines in javascript are immutable (numbers and logical values ​​are also immutable).

Another very simple solution to Upperize the first char of a string:

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

I also suggest reading this post: Understanding Javascript Immutable

Hope for this help

0
source

Source: https://habr.com/ru/post/1599305/


All Articles