Search This Blog

2023/04/25

How to capitalize first letter of each word in sentence using regx



var str = "I love javascript Very much"

var x = str.replace(/\w+/g, (matched, index, original) => {
console.log(matched)
return matched.charAt(0).toUpperCase() + matched.substring(1).toLowerCase()
});


console.log(x)

or

var str = "I love javascript Very much"
var arr = str.match(/\w+/g);

var res = ""
for (var i = 0; i < arr.length; i++) {
if(i != arr.length-1){
res = res + arr[i].charAt(0).toUpperCase() + arr[i].substring(1).toLowerCase() + " "
}else{
res = res + arr[i].charAt(0).toUpperCase() + arr[i].substring(1).toLowerCase()
}
}

console.log("[" + res + "]")

or

var str = "I love javascript Very much"
var arr = str.match(/\w+/g);

var res = arr.reduce((s,t)=>{
return s+ t.charAt(0).toUpperCase() + t.substring(1).toLowerCase() + " "
},"")

res = res.trim()
console.log("[" + res + "]")


No comments:

Post a Comment