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
Asked
Active
Viewed 65 times
-1
-
Possible duplicate of [Capitalize words in string](https://stackoverflow.com/questions/2332811/capitalize-words-in-string) – Kunal Mukherjee May 15 '19 at 07:50
1 Answers
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
-
-
You still have to **prototype** the function as shown in your link. I'll update my answer with the code aswell. – Oliver Nybo May 14 '19 at 09:57
-
@MadzQuestioning I added an example without prototyping `toUpperCaseWords` – Oliver Nybo May 15 '19 at 06:55