Im new to JS but I think the post title does its job. From what i saw by googling this problem, there's lots of ways to solve this issue. But basically, theres a text input field, the user writes 'paris'. how do i make 'paris' turn into 'Paris'. I need to get the input.value and change it. how? i dont hardcode the sentence, the user chooses the word and i get it as a text input value, is that a string or what? because i cant use for ex .charAt() to a "input.value" so it shouldnt be a string. Right?
Anyways, any help is appreciated, though i would appreciate more if you made it work with my first idea, and in case that idea is extremely wrong for some reason, explain why so i can learn and share the correct code.
CodePudding user response:
Splitting a string and uppercasing can be done in the following steps:
- Split the string by some delimiter -- in this case, we'll assume a space.
- Iterate over each word and uppercase the first letter while joining the rest of the characters.
- Combine the string by some delimiter -- we'll assume a space again.
Here is how it could be done:
const titlecaseWords = function(sentence) {
const splitSentence = sentence.split(' ');
for (let i = 0; i < splitSentence.length; i ) {
let word = splitSentence[i];
word = word.charAt(0).toUpperCase() word.slice(1);
splitSentence[i] = word;
}
return splitSentence.join(' ');
}
const sentence = 'this is a test';
const sentence1 = 'this is yet another test for the audience';
console.log(titlecaseWords(sentence));
console.log(titlecaseWords(sentence1));
Below are links to some JavaScript functions.
Splitting a string by a particular pattern
Edit If you want to use the "functional" functions, here is how it could be done:
const titlecaseWords = function(sentence) {
return sentence.split(' ')
.map(word => word.charAt(0).toUpperCase() word.slice(1))
.join(' ');
}
const sentence = 'this is a test';
const sentence1 = 'this is yet another test for the audience';
console.log(titlecaseWords(sentence));
console.log(titlecaseWords(sentence1));
Either one works. Here is documentation around the map
function.
CodePudding user response:
For your question what I understand truely, you want to uppercase first letter of input string that may or may not contain more than one word. Following this, this code might help
let userData = "lorem ipsum the world"
let newString = userData[0].toUpperCase() userData.slice(1)
alert(newString)
In case you need every first letter of each word uppercase, this might help
let userData = "lorem ipsum the world"
userData = userData.split(" ")
userData.forEach(function(word, index){
userData[index] = word[0].toUpperCase() word.slice(1)
})
newString = userData.join(" ")
alert(newString)