devorye
devorye

Reputation: 303

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);

Upvotes: 0

Views: 1032

Answers (3)

Anurag Uniyal
Anurag Uniyal

Reputation: 88747

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"

Upvotes: 1

Maciej Kozieja
Maciej Kozieja

Reputation: 1865

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))

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

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();
})

Upvotes: 0

Related Questions