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?
我是Javascript或正则表达式的新手。我需要将第一个单词字母替换为大写字母,我的代码就是这样,但它也会在特殊字符或其他字母(如ąčęėįš等)之后替换字母,并且我需要避免它并仅更改第一个字母。有人可以帮我解决这个问题吗?
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);
3 个解决方案
#1
0
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();
})
#2
0
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))
#3
0
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"
#1
0
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();
})
#2
0
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))
#3
0
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"