我有一些 JavaScript 在某些文本上运行转换大小写:
$(".container").click(function(){
text = text.toLowerCase().replace(/\b[a-z]/g, function(block){
return block.toUpperCase();
});
将容器 div 中的给定文本返回到句子大小写。但是,当在文本中使用撇号时,例如
can't get this to work
返回
Can'T Get This To Work
如何使撇号后的尾随 t 保持小写?
最佳答案
您的表达式不起作用的原因是 word boundary, \b
, 是 (^\w|\w$|\W\w|\w\W)
的缩写,不包含 '
字符,这意味着'
之后的字符,在您的例子中是 t
,被选中。
您可以将 \b
替换为 (^|\s)
,即 /(^|\s)[a-z]/g
,这将适用于您的情况:
$(".container").click(function() {
text = text.toLowerCase().replace(/(^|\s)[a-z]/g, function(block) {
return block.toUpperCase();
});
});
但是,最好的方法是使用正则表达式 \w\S*
,它将选择任何单词字符(即 [a-zA-Z0-9_]
) 后跟任何非字符串字符(即 [^\r\n\t\f ]
)。
这将允许您选择每个单词子串。从那里您可以将第一个字符大写并将其余字符转换为小写:
$(".container").click(function() {
text = text.replace(/\w\S*/g, function(word) {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
});
});
例如,以下代码段将返回:
"can't get this to work".replace(/\w\S*/g, function(word) {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
});
// > "Can't Get This To Work"
关于javascript - jQuery 转换句子大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42010706/