-1

Is there a way for us to perform UCWords just like this function into all elements of an array? I would prefer not to do a forloop into this. But if there are better and more elegant approach would appreciate any suggestion. I'm trying to implement this in NodeJs but I can't find the equivalent functionality of UCWord of PHP in JS/Node

MadzQuestioning
  • 3,341
  • 8
  • 45
  • 76

1 Answers1

0

You can do it with map

String.prototype.toUpperCaseWords = function() {
    return this.replace(/\w+/g, a => { 
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
    })
}

let myArray = ['some string', 'another string']
let mappedArray = myArray.map(element => element.toUpperCaseWords())
console.log(mappedArray)

Alternative without prototype

let myArray = ['some string', 'another string']
let mappedArray = myArray.map(element => {
    return element.replace(/\w+/g, a => { 
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
    })
})
console.log(mappedArray)
Oliver Nybo
  • 560
  • 1
  • 6
  • 24