capitalize a string in Javascript
Code snippet on how to capitalize a string in Javascript
let str = "this is a string";
let newStr = str.charAt(0).toUpperCase() + str.slice(1);
console.log(newStr);
This code capitalizes the first letter of the string ‘this is a string’. First, the code creates a variable called ‘str’ which holds the string ‘this is a string’. Then, the code creates a variable ‘newStr’ using the ‘charAt’ method which returns the first character of the string which in this case is ‘t’. To make the ‘t’ uppercase, the code uses the ‘toUpperCase’ method on the first character, then the rest of the character is appended to the ‘newStr’ variable with the ‘slice’ method. Finally, the new string is logged to the console with the ‘console.log’ method. The result is a capitalized version of the string, which is ‘This is a string’.