I was trying to take names from the user as input and tried to display the names so that the first character is capitalised and the remaining letters in lower case. PROBLEM: alert function at the last is not displaying the message. CODE: ''' var Name = prompt("Enter your name: ");
var Name = prompt("Enter your name: ");
var firstLetter = Name.Slice(0,1);
var finalFirstLetter = firstLetter.toUpperCase();
var remainingLetter = Name.Slice(0,Name.length);
var FinalRemainingLetter = remainingLetter.toLowerCase();
var captalisedName = finalFirstLetter FinalRemainingLetter;
alert("Hello, " CaptalisedName);
CodePudding user response:
Few notes,
- Javascript's
slicefunction is lowecased. - At the end, when you alert the output, your variable must be the same case as you declared
Run the snippet below, to see the desired output.
var Name = prompt("Enter your name: ");
var firstLetter = Name.slice(0,1);
var finalFirstLetter = firstLetter.toUpperCase();
var remainingLetter = Name.slice(1,Name.length);
var FinalRemainingLetter = remainingLetter.toLowerCase();
var captalisedName = finalFirstLetter FinalRemainingLetter;
alert("Hello, " captalisedName);
CodePudding user response:
This is the error message your code runs:
{
"message": "Uncaught TypeError: Name.Slice is not a function",
"filename": "https://stacksnippets.net/js",
"lineno": 13,
"colno": 24
}
Make sure you check the console when you run your code to see if any errors are being thrown, it can save a lot of headaches.
The function is not capitalized, so it would look something like this:
var name = prompt("Enter your name: ");
var firstLetter = name.slice(0,1).toUpperCase();
var remainingLetter = name.slice(1, name.length).toLowerCase();
var capitalizedName = firstLetter remainingLetter;
alert("Hello, " capitalizedName);
I would also try to follow some sort of naming convention to reduce capitalization errors. In the example above I'm using the javascript standards, which are camelCase for variables and functions, and UpperCamelCase is reserved for data types and classes.
Here is the same code with const , Have fun learning JS!
const name = prompt("Enter your name: ");
const firstLetter = name.substring(0, 1).toUpperCase();
const remainingString = name.substring(1).toLowerCase()
alert("Hello, " firstLetter remainingString);
CodePudding user response:
Maybe you could replace var with const. Sometimes this also solves the error.. Like this..
const name = prompt("Enter your name: ");
const firstLetter = name.substring(0, 1).toUpperCase();
const remainingString = name.substring(1).toLowerCase()
alert("Hello, " firstLetter remainingString);
