-3

This is about the title case algorithm which I extended further. I need the most efficient implementation in JavaScript. It should be extensible and scalable.

For example, I have a random array such as:

var arr = ["hell o", "3are", "you a","modern","332developer"];

If the element contents start with a number then it should ignore that index and move to the next index until it finds an initial letter and convert it to upper case. The remaining letters in the word should be in lower case. If there is space after a word in the content then it should consider that a new word and apply the same logic of applying upper case to that letter.

The results should be as below:

var arr = ["Hell O", "3Are", "You A","Modern","332Developer"];
beaker
  • 16,331
  • 3
  • 32
  • 49
AnaGua
  • 3
  • 5
  • You can find a solution for a single string here: https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript – eddyP23 Oct 03 '17 at 10:54
  • and you just need to run a loop on array elements to transform all of them, or just use `forEach` on array – eddyP23 Oct 03 '17 at 10:55
  • @eddyP23 the linked solution wouldn't work for `'3are'` (in the example it should become `'3Are'` with a capital 'A') – Federico klez Culloca Oct 03 '17 at 10:57
  • its about array not about strings, string are immutables but arrays are mutables. – AnaGua Oct 03 '17 at 11:00

2 Answers2

1

You can try something like this:

Logic:

  • Create a regex that will capture groups of characters.
  • Loop over array and capture these groups.
  • Replace/return title case value.

var arr = ["hell o", "3are", "you a","modern","332developer"];
var result = arr.map(function(s){
  return s.replace(/([a-z]+)/gi, function(match){
    return match[0].toUpperCase() + match.substring(1);
  })
});
console.log(result)
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

you can do

var arr = ["hell o", "3are", "you a","modern","332developer"];

arr = arr.map(e => e.replace(/([^\d\s])([^\s]+)?/g, (a, b, c) => {
    let ret = b.toUpperCase();
    if(c) ret += c.toLowerCase();
    return ret;
}));

console.log(arr);
marvel308
  • 10,288
  • 1
  • 21
  • 32