Hi could anyone plz tell me what is wrong in my code,first i convert the provided string into Array via split() method then i successfully converted the first letter of each sentence into upper case but when i returned my final result then it returned me a string without white spaces and when i tried to put the white spaces b/w each words then it gives me RESULT.PUSH() IS NOT A FUNCTION ERROR…what is wrong in my code???
function titleCase(str) {
var lowercase=str.toLowerCase();
var p = lowercase.split(" ")
var result = [];
for(var i=0;i<p.length;i++){
for(var j=0;j<p[i].length;j++){
if(j==0){
result+=p[i][j].toUpperCase();
}
else{
result+=p[i][j];
}
result.push(" "); //to include white spaces after each words
}
}
return result;
}
You cannot modify a string by just trying to change one character - strings in JavaScript are immutable. You have to do that conversion to uppercase and extract the remainder of the word and combine the first character and the remainder of the word.
First problem. You’ve declared var result = [] so your result is an array. And inside your inner for loop, you’re using += on an array.This will cast your result into string. Then later result.push will result in an error.
You’re logic for title casing individual words is correct. You just need a minor adjustments.
Inside your 1st for loop, create a variable called word and initialize it as an empty string ''. Then use += on this word inside your 2nd for loop.
When the inner for loop ends, push the word into result. So your result will contain title cased words.
Once all your loops are done their job, simply return result.join(' ') so that you will get a string that contains all the title cased words from result
function titleCase(str) {
var lowercase=str.toLowerCase();
var p = lowercase.split(" ")
var result = [];
for(var i=0;i<p.length;i++){
var word = '';
for(var j=0;j<p[i].length;j++){
if(j===0){
word+=p[i][j].toUpperCase();
} else{
word+=p[i][j];
}
}
result.push(word); //to include white spaces after each words
}
return result.join(' ');
}
Additionally, it often helps to use Array.prototype function to get improved readability. Here is an alternative
I believe his logic is correct for he’s iterating over a string and accessing the individual characters by index. He’s attempting to concat each of these characters to a new string. So string immutability isn’t a concern here.
Nope! i’m not changing array to string because in my knowledge(correct me if i’m wrong) and what i got when solving it on console when i called var p=str.split(" “) and returned ''p” it gave me array of string that’s why i’m accessing the indexes of “p” here…+= works fine but it returned me a string without white spaces which i did not get why?