将句子转换为 InitCap / 骆驼大小写 / 正确大小写
Convert a Sentence to InitCap / camel Case / Proper Case
我已经编写了这段代码。我想要一个小的正则表达式。
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());
小提琴
我想要什么
我"hello world".initCap() => Hello World
"hEllo woRld".initCap() => Hello World
上面的代码给了我解决方案,但我想要一个更好、更快的正则表达式解决方案
你可以试试:
- 将整个字符串转换为小写
- 然后使用 replace() 方法转换第一个字母,将每个单词的首字母转换为大写
str = "hEllo woRld";
String.prototype.initCap = function () {
return this.toLowerCase().replace(/(?:^|'s)[a-z]/g, function (m) {
return m.toUpperCase();
});
};
console.log(str.initCap());
如果要考虑带有撇号/破折号
的名称,或者句子之间的句点后可能会省略空格,那么您可能需要在正则表达式中使用 ''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());
输出:你好比莉-雷·奥马利-奥鲁克,请进来。
str="hello";
init_cap=str[0].toUpperCase() + str.substring(1,str.length).toLowerCase();
alert(init_cap);
其中 str[0] 给出 'h' 和 toUpperCase() 函数会将其转换为 'H',字符串中的其余字符通过 toLowerCase() 函数转换为小写。
较短的版本
const initcap = (str: string) => str[0].toUpperCase() + str.substring(1).toLowerCase();
如果您需要支持音调符号,这里有一个解决方案:
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 !")
输出:Voici Comment Gérer Les Caractères Accentués, C'Est Très Utile Pour Normaliser Les Prénoms !
相关文章:
- 我如何找到一个句子中的所有空格并替换忽略它们
- 如何使用jquery强制一个单词更改大小写等以保留品牌
- 使用jQuery检查提交时添加到句子中的单词
- 如何使用javascript标记句子
- 网络语音API-再次讲话(重置句子)
- 需要使用javascript获取输入文本,然后将其添加到句子中
- 如何使用Javascript在给定的句子中找到大写单词并在其前面添加一个字符
- JavaScript Regex(?i)选项中字符串大小写不敏感的部分不起作用
- 如何使后缀函数不区分大小写
- 获取特殊字符后没有单词的句子
- 我怎么能用css或(angular)javascript把句子分成两行,只在特定单词后面
- 找出句子中最长的单词——Javascript
- 如何在JavaScript中按大小写拆分字符串
- 将文本更改为驼色大小写
- 将句子大小写应用于可能包含HTML的字符串
- 将句子转换为 InitCap / 骆驼大小写 / 正确大小写
- 将句子或驼峰大小写单词转换为棘壳
- 在javascript中将字符串转换为句子大小写
- 标题大小写一个句子 - 哪个解决方案更好,为什么
- 我如何使用简单的子字符串函数在javascript标题大小写句子