只允许字符串中的第一个字母大写(正则表达式)
function toTitleCase(str){
var styleName = $("a.monogramClassSelected").attr("styleKey");
if (styleName == 'script') {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}).replace(/\s/, '');
} else {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
}
这有效(感谢下面的帮助) - 删除空格并将第一个字母大写。
但是,我需要不同的功能,并且第一次没有正确地提出我的问题。
我需要使用正则表达式只允许第一个字母大写。上面的字符串替换方法不能完全工作,因为用户可以通过使用空格来绕过该方法。所以他们可以有“两个”。我需要修改正则表达式,只允许第一个字母大写,而不管空格。 (并且第一个字母不必大写)
感谢大家到目前为止的帮助!
function toTitleCase(str){
var styleName = $("a.monogramClassSelected").attr("styleKey");
if (styleName == 'script') {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}).replace(/\s/, '');
} else {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
}
This works (thanks to help below) - to remove spaces and have the first letter capitalized.
However, I need different functionality and did not frame my question correctly the first time.
I need to use regex to only allow the first letter to be capitalized. The string replace method above does not work fully, as a user can get around the method by using a space. So they could have "To Two". I need to rework the regex to only allow the first letter to be capitalized, regardless of spaces. (and the first letter does not have to be capitalized)
thanks for everyone's help so far!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此正则表达式将零或恰好一个空格后跟大写字母的所有序列替换为仅该字母,同时保持文本的其余部分不变(允许多个空格)
可以通过 $1 访问组和替换字符串中的 $2。
示例
输入 " 一个从未犯过错误的人- Albert Einstein :)"
替换字符串 "一个从未犯过错误的人从未尝试过任何新东西 -AlbertEinstein :)"
如果您想删除多个空格而不是零或一个。 a 之前的空格然后在上面的表达式中使用大写字母
\s*
而不是\s{0,1}
。This regular expression replaces all sequences of the form zero or exactly one space followed by capital letter by only the letter while keeping the rest of the text untouched (with multiple spaces allowed)
The groups can be accessed by $1 and $2 in the replacement string.
Sample
Input " A person Who never made a mistake never tried anything new. - Albert Einstein :)"
Replaced string "A personWho never made a mistake never tried anything new. -AlbertEinstein :)"
In case you want to remove mutiple spaces instead of zero or one space preceding a capital letter then use
\s*
instead of\s{0,1}
in the above expression.这样就可以了:
This will do it:
要删除空格,这对我有用:
To just remove the spaces, this works for me: