1

I have stored a string in an array and want to check for white spaces that also stored in array. So that I can capitalize the each following word.

var arr = [];
arr = str.split("");
for(var i = 0; i < arr.length; i++) {
    if(arr[i] === ' ') {
        arr[i + 1].toUpperCase();
    }
}
erikvimz
  • 5,256
  • 6
  • 44
  • 60

5 Answers5

2

You're just missing an assignment:

var arr = [],
    str = 'abc def ghi jkl';
arr = str.split("");
for (var i = 0; i < arr.length; i++) {
  if (arr[i] === ' ') {
    arr[i + 1] = arr[i + 1].toUpperCase();
    // ^ You need to save the uppercase letter.
  }
}

// Also "uppecase" the first letter
arr[0] = arr[0].toUpperCase();

console.log(arr.join(''));

You can also shorten the code a bit:

var str = 'abc def ghi jkl',
    result = str.split(' ') // Split on `[space]`
      .map(function(word) { // Do something with every item in the array (every word)
        return word.charAt(0).toUpperCase() + // Capitalize the first letter.
               word.slice(1);                 // Add the rest of the word and return it.
      })
      .join(' '); //Make a string out of the array again.

console.log(result);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
0

You need to set the value of arr[i+1]:

var arr = [];
   arr = str.split("");
   for(var i=0; i<arr.length; i++)
   {
   if(arr[i]===' ')
          {
            arr[i+1]=arr[i+1].toUpperCase();
          }   
    }
grateful
  • 1,128
  • 13
  • 25
0

You can do it like this

var arr=[];
str="hello hi hello";
arr=str.split("");
arr1=arr.map(function(a,b){if(a==" "){arr[b+1]=arr[b+1].toUpperCase();} return(a)});
 arr1[0]=arr[0].toUpperCase();
 console.log(arr1);
Roli Agrawal
  • 2,356
  • 3
  • 23
  • 28
0

great piece of code @cerbrus now we can even lowercase other letters in the word except the first one by add :-

 var arr = [];
  arr = str.split(" ");

  str= arr.map(function(word)
          {
           return word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();     
   }).join(" ");
  return str;
-1
var a = ['', '     ', 'aa  '];

a.forEach(function(el){
    if(el.trim() == ''){
    console.log(el + ' -> white space');
  }else{
    var index = a.indexOf(el);
    a[index] = el.toUpperCase();
    console.log(a[index] + ' -> without white space');
  }
});
console.log(a);
mene
  • 372
  • 3
  • 17