0

I am attempting to uppercase the output string of a variable value as follows;

I have tried:

document.getElementById('namePlaceholder').innerHTML =  name.value.charAt(0).toUpperCase() + ' is here ';

name.value is a user input so my attempt is to uppercase the first letter of name. example

name.value = james

preferred outcome James is here.

is there a simple javascript solution for this?

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
agc
  • 173
  • 1
  • 16

2 Answers2

1

You cannot mutate strings directly as you are trying - you have to create a new string by concatenating the pieces you want:

document.getElementById('namePlaceholder').innerHTML =  
  name.value.charAt(0).toUpperCase() +   // will give you "J"
  name.value.slice(1).toLowerCase() +    // will give you "ames"
  ' is here ';

In lay terms, the slice(1) part says "grab everything after the first character". In more technical terms, if you have the name James, you can think of it as a series of letters (not an array, but kinda):

['J', 'a', 'm', 'e', 's'].

You can access individual letters like name[0], which will give you "J" and name[3] which will give you "e". You can then do name.slice(1), which will start at "a" and grab everything after it: "ames". To illustrate further, you could do name.slice(-2) to get the last 2 characters: "es". Or, if you want "me", you can do name.slice(2, 4).

Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
  • Have added 1 line as follows: name.value = name.value.charAt(0).toUpperCase() + // will give you "J" name.value.slice(1).toLowerCase() + (so I dont have to do it for each if statement.) Thanks! – agc Aug 28 '18 at 02:00
0

Using substring

document.getElementById('namePlaceholder').innerHTML =  
        name.value.charAt(0).toUpperCase() + 
        name.value.substr(1) +
        ' is here ';

Using Regular Expression:

document.getElementById('namePlaceholder').innerHTML =  
     name.value.replace(/^\w/, c => c.toUpperCase()); + ' is here ';

exactly similar to the following:

document.getElementById('namePlaceholder').innerHTML =  
     name.value.replace(/^\w/, function (chr) {
        return chr.toUpperCase();
     }); 
     + ' is here ';
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75