javascript 将句子转换为 InitCap / 骆驼案例 / 适当案例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19863402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:03:22  来源:igfitidea点击:

Convert a Sentence to InitCap / camel Case / Proper Case

javascriptregexstringcamelcasing

提问by Tushar Gupta - curioustushar

I have made this code. I want a small regexp for this.

我已经制作了这段代码。我想要一个小的正则表达式。

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
} 
String.prototype.initCap = function () {
    var new_str = this.split(' '),
        i,
        arr = [];
    for (i = 0; i < new_str.length; i++) {
        arr.push(initCap(new_str[i]).capitalize());
    }
    return arr.join(' ');
}
alert("hello world".initCap());

Fiddle

小提琴

What i want

我想要的是

"hello world".initCap() => Hello World

"hEllo woRld".initCap() => Hello World

“你好世界”.initCap() => 你好世界

"你好世界".initCap() => 你好世界

my above code gives me solution but i want a better and faster solution with regex

我上面的代码给了我解决方案,但我想要一个更好更快的正则表达式解决方案

回答by anubhava

You can try:

你可以试试:

str = "hEllo woRld";
String.prototype.initCap = function () {
   return this.toLowerCase().replace(/(?:^|\s)[a-z]/g, function (m) {
      return m.toUpperCase();
   });
};
alert(str.initCap());

回答by Bishnu Paudel

str="hello";
init_cap=str[0].toUpperCase() + str.substring(1,str.length).toLowerCase();

alert(init_cap);

where str[0] gives 'h' and toUpperCase() function will convert it to 'H' and rest of the characters in the string are converted to lowercase by toLowerCase() function.

其中 str[0] 给出 'h' 并且 toUpperCase() 函数将其转换为 'H' 并且字符串中的其余字符由 toLowerCase() 函数转换为小写。

回答by RJLyders

If you want to account for names with an apostrophe/dash or if a space could potentially be omitted after a period between sentences, then you might want to use \b (beg or end of word) instead of \s (whitespace) in your regular expression to capitalize any letter after a space, apostrophe, period, dash, etc.

如果您想用撇号/破折号来说明名称,或者在句子之间的句号后可能会省略一个空格,那么您可能需要使用 \b(词尾)而不是 \s(空格)正则表达式将空格、撇号、句点、破折号等后的任何字母大写。

str = "hEllo billie-ray o'mALLEY-o'rouke.Please come on in.";
String.prototype.initCap = function () {
   return this.toLowerCase().replace(/(?:^|\b)[a-z]/g, function (m) {
      return m.toUpperCase();
   });
};
alert(str.initCap());

OUTPUT: Hello Billie-Ray O'Malley-O'Rouke.Please Come On In.

输出:你好,Billie-Ray O'Malley-O'Rouke。请进。