Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected string.replace() result

Tags:

javascript

Why does this fail? Should I (somehow) escape letter i — this doesn't fail with other characters.

titleCase("I'm a little tea pot");

// Prints:   "i'm A Little Tea Pot"
// Expected: "I'm A Little Tea Pot"

function titleCase(str) {
  return str.split(' ').map(function(each) {
    return each.toLowerCase().replace(each[0], each[0].toUpperCase());
  }).join(' ');
}
like image 884
Jonatas Walker Avatar asked Dec 22 '25 16:12

Jonatas Walker


2 Answers

The .toLowerCase() is happening on the original value of each, so the .replace() may/will not give you the expected results.

If you split it out as a separate statement, it should work as expected:

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

As a slightly more efficient approach, it would also be better to move the .toLowerCase() to before the .map() call so it only needs to be called once, instead of once-per-word:

function titleCase(str) {
    str = str.toLowerCase();
    return str.split(' ').map(function(each) {
        return each.replace(each[0], each[0].toUpperCase());
    }).join(' ');
}
like image 94
newfurniturey Avatar answered Dec 24 '25 06:12

newfurniturey


You can try something like this:

Array.map

function titleCase(str) {  
  return str.split(' ').map(function(each) {
    return each.charAt(0).toUpperCase() + each.substring(1).toLowerCase();
  }).join(' ');
}

console.log(titleCase("I'm a little tea pot"));

Array.reduce

function titleCase(str) {  
  return str.split(' ').reduce(function(p,c) {
    return p + " " + toTitle(c);
  });
}

function toTitle(str){
  return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
}

console.log(titleCase("I'm a little tea pot"));
like image 31
Rajesh Avatar answered Dec 24 '25 07:12

Rajesh