2017-02-02 118 views
2

我有一些JavaScript运行上的一些文字转换情况:jQuery的转换句首字母大写

$(".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'

+1

的[字符串转换为JavaScript的标题下]可能的复制(http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript) –

回答

1

你的表达是不工作的原因是因为一个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" 
+0

谢谢,这正是我需要的! – Jordan