Having the first letter of a sentence uppercase lets the reader know the start of a sentence. There are different ways and techniques to make the first letter of a string uppercase in JavaScript. This article will provide different ways to make the first characters in uppercase.
Program to convert the first character of every word in a string into uppercase
Below is the JavaScript program that transforms the first character of each word to uppercase.
Code:
<html>
<head>
<title>Program to convert the first character of every word in a string into uppercase Using JavaScript</title>
<script>
// Javascript program to convert the first character of each word to uppercase in a sentence
function convert(str){
// Create an array of given String
let ch = str.split("");
for (let i = 0; i < str.length; i++) {
// If the first character of a word is found
if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' '){
// If it is in lower-case
if (ch[i] >= 'a' && ch[i] <= 'z'){
// Convert into Upper-case
ch[i] = String.fromCharCode( ch[i].charCodeAt(0) - 'a'.charCodeAt(0) +'A'.charCodeAt(0));
}
}
// If apart from the first character
//Anyone is in Upper-case
else if (ch[i] >= 'A' && ch[i] <= 'Z')
// Convert into Lower-Case
ch[i] = String.fromCharCode(ch[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0) );
}
// Convert the chararray to an equivalent String
let st =(ch).join("");
return st;
}
let str = "hey there how are you";
document.write(convert(str));
</script>
</head>
<body>
</body>
</html>
Output:
Here's how the program works
A function convert() is defined as taking a string as an input.
- The string gets divided into an array of words using the split() method.
- The code then iterates to find the first character of every word. After finding the first character, it gets converted to its uppercase character if it is in lowercase.
- Then it iterates again checking if any non-first character of a word is upper-case, it converts them into their lower-case character.
- After the completion of the task, the split string gets merged using the join() method
- The result gets printed using the document.write function.
Conclusion:
In the above article, we have learned the technique to make the first character of every word uppercase. Programmers often require such facility in database or form entry where the user data’s first letter or all letters need to convert to upper case. That is where you as a programmer should know how to create such a JavaScript program to make the first character of every string uppercase.