简体   繁体   中英

Capitalizing first letter after special character or letter

I am new to either Javascript or regex. I need to replace first word letter to the capital letter and my code does it, but it's also replacing the letter after special character or other letter (like ąčęėįš or etc.) and somehow I need to avoid it and change just only first letter. Could someone help me to solve this problem?

My code is here:

function capitalizeName(input) {
var name = input.val();
    name = name.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
})
input.val(name);

Then you need to remove word boundary with space or start anchor match.

name = name.toLowerCase().replace(/(^|\s)[a-z]/g, function(letter) {
    return letter.toUpperCase();
})

This should work for you:

or this

 console.log("tihi is some rčęėįš random typing. Is it good? maby has some minor-bugs but at least works" .replace(/\\w.*?\\W/g, x => x[0].toUpperCase() + x.substr(1))) 

you have to add non world char at the end for this to work.

 const data = "tihi is some rčęėįš random typing. Is it good? maby has some minor-bugs but at least works." const capitalize = data => (data + ' ').replace(/\\w.*?\\W/g, x => x[0].toUpperCase() + x.substr(1)).substr(0, data.length) console.log(capitalize(data)) 

I prefer a non-regex answer to all such questions, for fun and mostly you don't need complex regexes

"java script is cool".split(" ").map(function(w){return w[0].toUpperCase()+w.substr(1)}).join(" ")
"Java Script Is Cool"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM