[英]Convert a Sentence to InitCap / camel Case / Proper Case
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());
What i want我想要的是
"hello world".initCap() => Hello World
“你好世界”.initCap() => 你好世界
"hEllo woRld".initCap() => Hello World
"hHello woRld".initCap() => 你好世界
my above code gives me solution but i want a better and faster solution with regex我上面的代码给了我解决方案,但我想要一个更好更快的正则表达式解决方案
You can try:你可以试试:
str = "hEllo woRld"; String.prototype.initCap = function () { return this.toLowerCase().replace(/(?:^|\\s)[az]/g, function (m) { return m.toUpperCase(); }); }; console.log(str.initCap());
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() 函数转换为小写。
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.如果您想用撇号/破折号来说明名称,或者如果在句子之间的句号后可能会省略一个空格,那么您可能需要在您的正则表达式将空格、撇号、句点、破折号等后的任何字母大写。
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。请进来。
If you need to support diacritics, here is a solution:如果您需要支持变音符号,这里有一个解决方案:
function initCap(value) {
return value
.toLowerCase()
.replace(/(?:^|[^a-zØ-öø-ÿ])[a-zØ-öø-ÿ]/g, function (m) {
return m.toUpperCase();
});
}
initCap("Voici comment gérer les caractères accentués, c'est très utile pour normaliser les prénoms !")
OUTPUT: Voici Comment Gérer Les Caractères Accentués, C'Est Très Utile Pour Normaliser Les Prénoms !
输出:
Voici Comment Gérer Les Caractères Accentués, C'Est Très Utile Pour Normaliser Les Prénoms !
Shorter version较短的版本
const initcap = (str: string) => str[0].toUpperCase() + str.substring(1).toLowerCase();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.