Why are these outputting different strings?!

Why are these outputting different strings?!
0

#1

Hello, this is my first post so bear with me & if this is wrong section then pls move it to the right one. Can any one let me know why the below two blocks of code outputting different strings. I mean the logic is same, they are written in different way(the first one is more shorter form than the second one).

function titleCase(str) {
  var strArray = str.split(' ');
  var cStrArray = strArray.map(function(val){
    return (val.toLowerCase().replace(val[0],val[0].toUpperCase()));
  });
 return  cStrArray.join(' ');
}

titleCase("I'm Nothing");

Which outputs “i’m Nothing”. (sentence starts with lower case ‘i’).

function titleCase(str) {
  var strArray = str.split(' ');
  var cStrArray = strArray.map(function(val){
    val = val.toLowerCase();
    return val.replace(val[0],val[0].toUpperCase());
  });
 return  cStrArray.join(' ');
}

titleCase("I'm Nothing");

Which is outputting “I’m Nothing”. (sentence starts with upper case ‘i’).


#2

I get: 'i\'m nothing'

EDIT: It does so because the value of val is not yet updated when replace is run. So first you val.toLowerCase() (which returns "i'm nothing") and on that string you use replace. But you call it with val[0] which is still the capital letter you entered (I’m Nothing). Since you just use replace on the lowercase version it won’t find a match.

EDIT2: @jenovs was slightly to quick…


#3

In your first example this line:

return (val.toLowerCase().replace(val[0],val[0].toUpperCase()));

is basically this:

var newString = val.toLowerCase();
return newString.replace(val[0], val[0].toUpperCase)

val is never changed, newString is all lowercase and you try to find val[0] (which is still uppercase) in the newString.