Capitalize the first letter of each string [duplicate] - javascript

This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 5 years ago.
I've been trying to capitalize the first letter of each word in a string, but it says TypeError: Cannot assign to read only property '0' of string 'i' . My logic looks fine but surely the way I'm doing this is not right. Any suggestions.
function titleCase(str) {
str = str.toLowerCase();
var word = str.split(" ");
// console.log(word[0][0]);
for (var i = 0; i < word.length - 1; i++) {
word[i][0] = word[i][0].toUpperCase();
}
console.log(word);
return word;
}
titleCase("I'm a little tea pot");

Try like so: (see comments in code)
function titleCase(str) {
str=str.toLowerCase();
var word = str.split(" ");
for (var i=0; i < word.length; i++) { // you don't need -1 here as you had
word[i] = word[i].charAt(0).toUpperCase() + word[i].slice(1); // see changes in this line
}
console.log(word);
return word;
}
titleCase("I'm a little tea pot");

Strings have a replace method that accepts a function:
var s = 'foo bar fum i am sparticus 23!!';
console.log(s.replace(/\b\w/g, function(s){return s.toUpperCase()}));

You can directly convert your string into what you want by inbuilt array function.
Using map function you will get it directly no need to run for loop.
("I'm a little tea pot")
.split(" ")
.map(function(d){
return d[0].toUpperCase()+d.substring(1,d.length)
}).join(" ")

You can combine split and map functions to achieve this.
function titleCase(str) {
return str.toLowerCase().split(" ").map(function(word) {
var _word = word.split("");
_word[0] = _word[0].toUpperCase();
return _word.join("");
}).join(" ");
}
console.log(titleCase("I'm a little tea pot"));

You can use map function to create an array of modified words and join to recreate the string
function titleCase(str) {
str = str.toLowerCase();
var word = str.split(" ");
var x = word.map(function(item) {
return item.charAt(0).toUpperCase() + item.substring(1, item.length);
}).join(" ");
return x
}
console.log(titleCase("I'm a little tea pot"));
Using only CSS
#test {
text-transform: capitalize
}
<div id="test"> I'm a little tea pot</div>

With split, array map and reduce:
var str = "I'm a little tea pot";
var res = str.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.substr(1))
.reduce((m, o) => { m = m + " " + o; return m }, "")
console.log(res);
Join can be also used instead of reduce:
var str = "I'm a little tea pot";
var res = str.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.substr(1))
.join(" ");
console.log(res);

Related

What's wrong with my code? first letter of each word should capitalized

function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2;
for(var i = 0; i < str1.length; i++){
str2 = str1[i].toLowerCase().replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
What's wrong with my code? str2.join is not a function
Easiest way to go about this is to split the string on every space, then set the first letter of each element in the array to the capitalized version of the letter and join it back.
What you are doing is assigning the value of the result to str2, having a string type rather than an array, that is why join is not working for you.
function titleCase(str) {
const words = str.split(' ');
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
return words.join(' ');
}
A slightly different variant with some ES6 favor to it:
const titleCase = str => {
const result = [];
for (const word of str.split(' ')) {
result.push(word[0].toUpperCase() + word.slice(1));
}
return result.join(' ');
};
If you want to ensure space characters such as tabs, newlines etc. work, you can split using your regex or replace all whitespace characters with spaces as a first step, e.g.:
const words = str.replace(/\s/g, ' ').split(' ').filter(word => word !== '');
function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2 = [];
for(var i = 0; i < str1.length; i++){
str2[i] = str1[i].replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
This is a simple solution to your problem. However, there are many ways to get the same result this is one of them.
function capitalize(str) {
let str2 = str[0].toUpperCase();
return str.replace(str[0], str2);
}

How to capitalize the first letter of each word in an array in JavaScript? [duplicate]

This question already has answers here:
Trying to capitalize the first character in array of strings, why this is not working?
(16 answers)
Closed 6 years ago.
I've been trying for the last hours to understand why my code is not working well. Instead of capitalizing only the first letters of each item in the array my code capitalizes all the letters in the array.
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var i = 0; i < str.length; i++){
str[i] = str[i].split(' ');
str[i][0] = str[i][0].toUpperCase();
str[i] = str[i].join(' ');
}
return str.join(' ');
}
titleCase("I'm a little tea pot");
If you want a more functional way:
const titleCase = str => (
str.split(' ').map(c => c.slice(0, 1).toUpperCase() + c.slice(1)).join(' ')
);
titleCase("I'm a little tea pot");
Try:
function titleCase(str)
{
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}

The mission is to turn each word's first letter into capital (Javascript)

The code below doesn't work why?
function titleCase(str){
var newStr = str.split(" "); //split string turn it into seperated words[]
var resutl;
for(vari=0; i < newStr.length; i++){ //iterate all words
var result = newStr[i].charAt(0).toUpperCase +
// find first letter and turn it into capital
newStr[i].subString(1).toLowerCase();
}
return result.join(" ");
}
result in your code is a string, not an array. you cannot join a string.
each iteration of the loop you are replacing the variable result with a new word. you need to initialize a result array [] and push each result onto the array, then join the array after the loop has completed.
The result needs to be an array and also you have some typos in your code, e.g. missing ()
function titleCase(str) {
var newStr = str.split(" ");
var result = [];
for (var i = 0; i < newStr.length; i++) {
result.push(newStr[i].charAt(0).toUpperCase() + newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
var str = 'hELLO wORLD';
document.write(titleCase(str));
Try using regular expression
var data = "The mission is to turn each word's first letter into capital";
data = data.replace(/ (.)/g,function(w){return w.toUpperCase()});
drawback :this will not capitalize the first character.
Explode the string on spaces and iterate it with the function below:
function ucfirst(str) {
str += ''; // make sure str is really a string
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
You may try this :
function titleCase(str){
var newStr = str.split(" ");
var result = [];
for(var i=0; i < newStr.length; i++){
result.push(newStr[i].charAt(0).toUpperCase() +
newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
Another Approach:
function titleCase(str){
var words = str.split(" ");
return words.map(function(word){
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(" ");
}

capitalizing only first letter in a contraction

My challenge is to capitalize the first letter of each word in a string while making sure all the other letters are lowercase. I have spent more hours then I'm willing to admit on this and my code is shown below. It's about 95% complete.
It's only flaw is that it returns contractions like "I'm" as "I'M". For some reason it sees contractions as two separate words. I tested this my putting a console.log immediately after the step that capitalizes the first letter (I have commented it out in the example). it returns that it is capitalizing both "I" and "M" in the same step. How do I get get it change only the "I"?
function titleCase(str) {
str = str.toLowerCase(); //make everything lowercase
str = str.split(" "); //make the string to array
for(i = 0; i < str.length; i++){
var strItem = str[i]; //take item in array
strItem = strItem.replace(/\b./g, function(m){ return m.toUpperCase(); }); //capitalize it
//console.log(strItem);
str[i] = strItem; //put changed item back into array
}
str = str.join(" "); //turn array back into string
return str;
}
titleCase("I'm a little tea pot");
Thank you for your time.
Your problem seems to be that you are using a global match in your replacer expression.
Remove the g.
function titleCase(str) {
str = str.toLowerCase(); // Make everything lowercase
str = str.split(/\s+/); // Make the string to array
for (var i = 0; i < str.length; i++) {
var strItem = str[i]; // Take item in array
strItem = strItem.replace(/\b./,
function(m) {
return m.toUpperCase(); // Capitalize it
}
);
str[i] = strItem; // Put changed item back into array
}
return str.join(" "); // Turn array back into string
}
document.body.innerHTML = titleCase("I'm a little tea pot");
Simplified
You can create a capitalCase function and use it as the mapping (callback) function for each word.
function titleCase(str) {
return str.split(/\s+/).map(captitalCase).join(' ');
}
function captitalCase(str) {
return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
}
document.body.innerHTML = titleCase("I'm a little tea pot");
Preserve White-Space
If you want to preserve white-space, you can replace all sequences non-white-space characters with their respective capitalCase equivalent.
function titleCase(str) {
return str.replace(/(\S+)/g, function(m) {
return captitalCase(m);
});
}
function captitalCase(str) {
return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
}
document.body.innerHTML = titleCase("I'm a little \n tea pot");
body {
white-space: pre;
}
What I suggest, is that you use <string>.charAt(<index>) to get the first letter of a string, and that <string>.slice(<index>) can give you a portion of a string.
Hint: After taking each word, you could take the first letter using charAt(), uppercase it, then take the rest slice of your string and lowercase it.
UPDATE:
Answer:
function upperFirstLetterInWords(str) {
var totalString = "";
//Take words from sentence -
//Use regex /\s+/g for many spaces in sentence.
var words = str.split(" ");
//Take each word...
//Using for loop as we have an array and it is
//more efficient than foreach loop or lambda.
for(var i = 0; i < words.length; ++i) {
//Make your changes here.javascript:;
totalString += words[i].charAt(0).toUpperCase() +
words[i].slice(1).toLowerCase() +
" ";
}
//Remove last space.
return totalString.trim();
}
console.log(upperFirstLetterInWords("I'm A LitTle TEa POt."));
Out of curiosity, I wanted to see if I could come up with an alternative javascript solution without using regex:
var selectedParagraph = document.getElementsByTagName('p')[1];
var textUC = [];
function toTitleCase(element) {
var textLC = element.innerHTML.toLowerCase().split(' ');
for (var i = 0; i < textLC.length; i++) {
textUC[i] = textLC[i].substr(0,1).toUpperCase() + textLC[i].substr(1);}
element.innerHTML = textUC.join(' ');
}
window.onload = toTitleCase(selectedParagraph);
<p>I'm a little tea pot</p>
<p>I'm a little tea pot</p>

Capitalize the first letter of every word

I want to use a javascript function to capitalize the first letter of every word
eg:
THIS IS A TEST ---> This Is A Test
this is a TEST ---> This Is A Test
this is a test ---> This Is A Test
What would be a simple javascript function
Here's a little one liner that I'm using to get the job done
var str = 'this is an example';
str.replace(/\b./g, function(m){ return m.toUpperCase(); });
but John Resig did a pretty awesome script that handles a lot of cases
http://ejohn.org/blog/title-capitalization-in-javascript/
Update
ES6+ answer:
str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
There's probably an even better way than this. It will work on accented characters.
function capitalizeEachWord(str)
{
var words = str.split(" ");
var arr = [];
for (i in words)
{
temp = words[i].toLowerCase();
temp = temp.charAt(0).toUpperCase() + temp.substring(1);
arr.push(temp);
}
return arr.join(" ");
}
"tHiS iS a tESt".replace(/[^\s]+/g, function(str){
return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
});
Other variant:
"tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){
return $1.toUpperCase()+$2.toLowerCase();
});
This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.
function capitalize(str){
var strArr = str.split(" ");
var newArr = [];
for(var i = 0 ; i < strArr.length ; i++ ){
var FirstLetter = strArr[i].charAt(0).toUpperCase();
var restOfWord = strArr[i].slice(1);
newArr[i] = FirstLetter + restOfWord;
}
return newArr.join(' ');
}
take a look at ucwords from php.js - this seems to be kind of what you're looking for. basically, it's:
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
note that THIS IS A TEST will return THIS IS A TEST so you'll have to use it like this:
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring.toLowerCase());
or modify the function a bit:
function ucwords (str) {
str = (str + '').toLowerCase();
return str.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring); // This Is A Test
This will capitalize every word seperated by a space or a dash
function capitalize(str){
str = str.toLowerCase();
return str.replace(/([^ -])([^ -]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
}
Examples :
i lOvE oRanges => I Love Oranges
a strAnge-looKing syntax => A Strange-Looking Syntax
etc
If you don't mind using a library, you could use Sugar.js capitalize()
capitalize( all = false ) Capitalizes the first character in the
string and downcases all other letters. If all is true, all words in
the string will be capitalized.
Example:
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
you can also use below approach using filter:
function Ucwords(str){
var words = str.split(' ');
var arr = [];
words.filter(function(val){
arr.push(val.charAt(0).toUpperCase()+ val.substr(1).toLowerCase());
})
console.log(arr.join(" ").trim());
return arr.join(" ").trim();
}
Ucwords("THIS IS A TEST") //This Is A Test
Ucwords("THIS ") //This
{
String s = "this is for testing";
String sw[] = s.split("\\s");
String newS = "";
for(int i=0; i<=sw.length-1; i++)
{
String first = sw[i].substring(0,1);
String last = sw[i].substring(1);
newS+= first.toUpperCase()+last+" ";
}
System.out.println(newS);
}

Categories