如何使用 JavaScript 将字符串中每个单词的首字母大写?
How can I capitalize the first letter of each word in a string using JavaScript?
我正在尝试编写一个将字符串中每个单词的首字母大写的函数(将字符串转换为首字母大写)。
例如,当输入为 "I'm a little tea pot"
时,我希望输出为 "I'm A Little Tea Pot"
。但是,函数 returns "i'm a little tea pot"
.
这是我的代码:
function titleCase(str) {
var splitStr = str.toLowerCase().split(" ");
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(" ");
}
return str;
}
console.log(titleCase("I'm a little tea pot"));
你把复杂的事情变得很简单了。您可以将此添加到 CSS:
.capitalize {
text-transform: capitalize;
}
在 JavaScript 中,您可以将 class 添加到元素
document.getElementById("element").className = "capitalize";
您没有再次将您的更改分配给数组,所以您所有的努力都是徒劳的。试试这个:
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
此例程将处理带连字符的单词和带撇号的单词。
function titleCase(txt) {
var firstLtr = 0;
for (var i = 0;i < text.length;i++) {
if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
if (text.charAt(i) == "'") {
if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1)))
firstLtr = 3;
else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2)))
firstLtr = 3;
}
if (firstLtr == 3)
firstLtr = 1;
else
firstLtr = 0;
}
if (firstLtr == 2) {
firstLtr = 1;
text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
}
else {
text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
}
}
}
titleCase("pAt o'Neil's");
// returns "Pat O'Neil's";
function titleCase(str) {
var myString = str.toLowerCase().split(' ');
for (var i = 0; i < myString.length; i++) {
var subString = myString[i].split('');
for (var j = 0; j < subString.length; j++) {
subString[0] = subString[0].toUpperCase();
}
myString[i] = subString.join('');
}
return myString.join(' ');
}
ECMAScript 6版本:
title
.split(/ /g).map(word =>
`${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
.join(" ");
如果您可以使用第三方库,那么 Lodash 可以为您提供辅助功能。
https://lodash.com/docs/4.17.3#startCase
_.startCase('foo bar');
// => 'Foo Bar'
_.startCase('--foo-bar--');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
/* 1. Transform your string into lower case
2. Split your string into an array. Notice the white space I'm using for the separator
3. Iterate the new array, and assign the current iteration value (array[c]) a new formatted string:
- With the sentence: array[c][0].toUpperCase() the first letter of the string converts to upper case.
- With the sentence: array[c].substring(1) we get the rest of the string (from the second letter index to the last one).
- The "add" (+) character is for concatenate both strings.
4. return array.join(' ') // Returns the formatted array like a new string. */
function titleCase(str){
str = str.toLowerCase();
var array = str.split(' ');
for(var c = 0; c < array.length; c++){
array[c] = array[c][0].toUpperCase() + array[c].substring(1);
}
return array.join(' ');
}
titleCase("I'm a little tea pot");
ECMAScript 6版本:
const toTitleCase = (phrase) => {
return phrase
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);
原始代码:
function capi(str) {
var s2 = str.trim().toLowerCase().split(' ');
var s3 = [];
s2.forEach(function(elem, i) {
s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
});
return s3.join(' ');
}
capi('JavaScript string exasd');
我用了 replace()
和正则表达式:
function titleCase(str) {
var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());
console.log(newStr);
}
titleCase("I'm a little tea pot")
也是一个不错的选择(特别是如果您使用 freeCodeCamp):
function titleCase(str) {
var wordsArray = str.toLowerCase().split(/\s+/);
var upperCased = wordsArray.map(function(word) {
return word.charAt(0).toUpperCase() + word.substr(1);
});
return upperCased.join(" ");
}
或者可以使用 replace() 来完成,将每个单词的第一个字母替换为它的“大写”。
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
titleCase("I'm a little tea pot");
-
您可以简单地使用正则表达式函数来更改每个字母的大小写。通过 V8 JIST 优化,这应该被证明是快速和内存高效的。
// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})
或者,作为函数:
// Only works for Latin-I strings
var fromCharCode = String.fromCharCode;
var firstLetterOfWordRegExp = /\b[a-z]|['_][a-z]|\B[A-Z]/g;
function toLatin1UpperCase(x){ // avoid frequent anonymous inline functions
var charCode = x.charCodeAt(0);
return charCode===39 ? x : fromCharCode(charCode^32);
}
function titleCase(string){
return string.replace(firstLetterOfWordRegExp, toLatin1UpperCase);
}
根据 this benchmark,代码比 Chrome 中的下一个最佳解决方案快 33% 以上。
<textarea id="input" type="text">I'm a little tea pot</textarea><br /><br />
<textarea id="output" type="text" readonly=""></textarea>
<script>
(function(){
"use strict"
var fromCode = String.fromCharCode;
function upper(x){return x[0]==="'"?x:fromCode(x.charCodeAt(0) ^ 32)}
(input.oninput = function(){
output.value = input.value.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, upper);
})();
})();
</script>
请检查下面的代码。
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
var nstr = "";
for (var i = 0; i < splitStr.length; i++) {
nstr += (splitStr[i].charAt(0).toUpperCase()+ splitStr[i].slice(1) + "
");
}
console.log(nstr);
}
var strng = "this is a new demo for checking the string";
titleCase(strng);
由于可读性,我通常不喜欢使用正则表达式,而且我尽量避免循环。我认为这有点可读性。
function capitalizeFirstLetter(string) {
return string && string.charAt(0).toUpperCase() + string.substring(1);
};
@somethingthere 提出的解决方案的更紧凑(和现代)重写:
let titleCase = (str => str.toLowerCase().split(' ').map(
c => c.charAt(0).toUpperCase() + c.substring(1)).join(' '));
document.write(titleCase("I'm an even smaller tea pot"));
自 ECMA2017 或 ES8 起
const titleCase = (string) => {
return string
.split(' ')
.map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length))
.join(' ');
};
let result = titleCase('test test test');
console.log(result);
解释:
1. 首先,我们将字符串 "test test test" 传递给我们的函数 "titleCase".
2. 我们在 space 基础上拆分字符串,因此第一个函数 "split" 的结果将是 ["test","test","test"]
3. 当我们得到一个数组时,我们使用 map 函数来操作数组中的每个单词。我们将第一个字符大写并向其添加剩余字符。
4. 最后,我们使用 space 连接数组,因为我们按 sapce 拆分字符串。
这是使用 map
函数的基本方法,它与公认的答案相同,但没有 for-loop
。因此,为您节省几行代码。
function titleCase(text) {
if (!text) return text;
if (typeof text !== 'string') throw "invalid argument";
return text.toLowerCase().split(' ').map(value => {
return value.charAt(0).toUpperCase() + value.substring(1);
}).join(' ');
}
console.log(titleCase("I'm A little tea pot"));
除了尝试将所有单词的所有首字母(即通过正则表达式定义 \w+
)转换为大写外,下面的函数不会更改字符串的任何其他部分。
这意味着它 不一定 将单词转换为 Titlecase,但确实如问题标题所述:"Capitalize First Letter Of Each Word In A String - JavaScript"
- 不要拆分字符串
- 通过等同于
[A-Za-z0-9_]+
的正则表达式 \w+
确定每个 word
- 仅将函数
String.prototype.toUpperCase()
应用于每个单词的第一个字符。
function first_char_to_uppercase(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
});
}
示例:
first_char_to_uppercase("I'm a little tea pot");
// "I'M A Little Tea Pot"
// This may look wrong to you, but was the intended result for me
// You may wanna extend the regex to get the result you desire, e.g., /[\w']+/
first_char_to_uppercase("maRy hAd a lIttLe LaMb");
// "MaRy HAd A LIttLe LaMb"
// Again, it does not convert words to Titlecase
first_char_to_uppercase(
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
// "ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples"
first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
// "…N1=OrangesFromSPAIN&&N2!='A Sub-String Inside'"
first_char_to_uppercase("snake_case_example_.Train-case-example…");
// "Snake_case_example_.Train-Case-Example…"
// Note that underscore _ is part of the RegEx \w+
first_char_to_uppercase(
"Capitalize First Letter of each word in a String - JavaScript"
);
// "Capitalize First Letter Of Each Word In A String - JavaScript"
编辑 2019-02-07:如果你想要实际的 Titlecase(即只有第一个字母大写,所有其他字母小写):
function titlecase_all_words(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});
}
显示两者的示例:
test_phrases = [
"I'm a little tea pot",
"maRy hAd a lIttLe LaMb",
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
"…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
"snake_case_example_.Train-case-example…",
"Capitalize First Letter of each word in a String - JavaScript"
];
for (el in test_phrases) {
let phrase = test_phrases[el];
console.log(
phrase,
"<- input phrase\n",
first_char_to_uppercase(phrase),
"<- first_char_to_uppercase\n",
titlecase_all_words(phrase),
"<- titlecase_all_words\n "
);
}
// I'm a little tea pot <- input phrase
// I'M A Little Tea Pot <- first_char_to_uppercase
// I'M A Little Tea Pot <- titlecase_all_words
// maRy hAd a lIttLe LaMb <- input phrase
// MaRy HAd A LIttLe LaMb <- first_char_to_uppercase
// Mary Had A Little Lamb <- titlecase_all_words
// ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples <- input phrase
// ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples <- first_char_to_uppercase
// Examplex: Camelcase/Uppercase&Lowercase,Exampley:N0=Apples <- titlecase_all_words
// …n1=orangesFromSPAIN&&n2!='a sub-string inside' <- input phrase
// …N1=OrangesFromSPAIN&&N2!='A Sub-String Inside' <- first_char_to_uppercase
// …N1=Orangesfromspain&&N2!='A Sub-String Inside' <- titlecase_all_words
// snake_case_example_.Train-case-example… <- input phrase
// Snake_case_example_.Train-Case-Example… <- first_char_to_uppercase
// Snake_case_example_.Train-Case-Example… <- titlecase_all_words
// Capitalize First Letter of each word in a String - JavaScript <- input phrase
// Capitalize First Letter Of Each Word In A String - JavaScript <- first_char_to_uppercase
// Capitalize First Letter Of Each Word In A String - Javascript <- titlecase_all_words
text-transform: capitalize;
CSS 知道了:)
在 ECMAScript 6 中,使用箭头函数的单行答案:
const captialize = words => words.split(' ').map( w => w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')
function LetterCapitalize(str) {
return str.split(" ").map(item=>item.substring(0,1).toUpperCase()+item.substring(1)).join(" ")
}
下面是另一种将字符串中每个单词的第一个字母大写的方法。
使用 prototype
.
为字符串对象创建自定义方法
String.prototype.capitalize = function() {
var c = '';
var s = this.split(' ');
for (var i = 0; i < s.length; i++) {
c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
}
return c;
}
var name = "john doe";
document.write(name.capitalize());
let cap = (str) => {
let arr = str.split(' ');
arr.forEach(function(item, index) {
arr[index] = item.replace(item[0], item[0].toUpperCase());
});
return arr.join(' ');
};
console.log(cap("I'm a little tea pot"));
快速可读版本参见基准测试http://jsben.ch/k3JVz
我觉得这样应该会更快;因为它不会拆分字符串并再次加入它;仅使用正则表达式。
var str = text.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
解释:
(^\w{1})
: 匹配字符串的第一个字符
|
: 或
(\s{1}\w{1})
:匹配一个 space 之后的一个字符
g
:匹配全部
- match => match.toUpperCase(): 替换为可以带函数,所以;用大写匹配替换匹配
function titleCase(str) {
//First of all, lets make all the characters lower case
let lowerCaseString = "";
for (let i = 0; i < str.length; i++) {
lowerCaseString = lowerCaseString + str[i].toLowerCase();
}
//Now lets make the first character in the string and the character after the empty character upper case and leave therest as it is
let i = 0;
let upperCaseString = "";
while (i < lowerCaseString.length) {
if (i == 0) {
upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase();
} else if (lowerCaseString[i - 1] == " ") {
upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase();
} else {
upperCaseString = upperCaseString + lowerCaseString[i];
}
i = i + 1;
}
console.log(upperCaseString);
return upperCaseString;
}
titleCase("hello woRLD");
这里有一个完整而简单的解决方案:
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index
+ replacement.length);
}
var str = 'k j g u i l p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
for(let i = 0; i < str.length-1; i++) {
if(str[i] === ' ' && str[i+1] !== '')
str = str.replaceAt(i+1, str[i+1].toUpperCase());
}
return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));
ES6 语法
const captilizeAllWords = (sentence) => {
if (typeof sentence !== "string") return sentence;
return sentence.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
captilizeAllWords('Something is going on here')
最短的一行(也极快):
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
解释:
^\w
: 字符串的第一个字符
|
: 或
\s\w
: 空格后的第一个字符
(^\w|\s\w)
捕获模式。
g
标记:匹配所有匹配项。
如果您想确保其余部分是小写:
text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
用法示例:
const toTitleCase = str => str.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
console.log(toTitleCase("heLLo worLd"));
这里我使用了三个函数toLowerCase()
、toUpperCase()
和replace(regex,replacer)
function titleCase(str) {
return str.toLowerCase().replace(/^(\w)|\s(\w)/g, (grp) => grp.toUpperCase());
}
titleCase("I'm a little tea pot");
这是一种简单的转换方法,能够传递一个值以获得所需的输出。
String.prototype.toChangeCase = function (type) {
switch (type) {
case 'upper-first':
return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
case 'upper-each':
return this.split(' ').map(word => {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
}).join(' ');
default:
throw Error(`In order to get the output pass a value 'upper-first', 'upper-each'`);
}
}
产出
"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-first')
"Capitalize first letter of each word in a sstring"
"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-each')
"Capitalize First Letter Of Each Word In A Sstring"
"Capitalize First Letter Of Each Word In A String".toChangeCase()
VM380:12 Uncaught Error: In order to get the output pass a value 'upper-first', 'upper-each'
at String.toChangeCase (<anonymous>:12:19)
at <anonymous>:16:52
这里我使用了replace()
函数
function titleCase(str){
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
您可以使用现代 JS 语法,让您的生活更轻松。这是我针对给定问题的代码片段:
const capitalizeString = string => string.split(' ').map(item => item.replace(item.charAt(0), item.charAt(0).toUpperCase())).join(' ');
capitalizeString('Hi! i am aditya shrivastwa')
let string = "I'm a little tea pot";
现在,创建一个将字符串作为参数的函数。
function titleCase(str) {
return str.split(" ").map(s => s.charAt(0).toUpperCase() + s.substr(1).toLowerCase()).join(" ")
}
输出
titleCase(string); // "I'm A Little Tea Pot"
你可以用这样简单的方式在一行中使用带有 toUpperCase 的 map:
text.split(' ').map(w => { let t = w.split(''); t[0] = t[0].toUpperCase(); return t.join('') }).join(' ')
TypeScript 粗箭头 FTW
export const formatTitleCase = (string: string) =>
string
.toLowerCase()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.substring(1))
.join(" ");
我已经使用下面的代码完成了此操作,希望对您有所帮助:
<p id="p1">This is a paragraph.</p>
<script>
const capitalize = (mySentence) => {
const words = mySentence.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join(" ");
};
const result = capitalize('This is a sample text');
document.getElementById("p1").innerHTML = result;
</script>
这里是简单的一行
const ucFirst = t => t.replace(/(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g, c => c.toUpperCase());
注意它只改变每个单词首字母的大小写,你可能想这样使用它:
console.log(ucFirst('foO bAr'));
// FoO BAr
console.log(ucFirst('foO bAr'.toLowerCase()));
// Foo Bar
// works with accents too
console.log(ucFirst('éfoO bAr'));
// ÉfoO BAr
或者基于String.prototype
,这里有一个可以处理多种模式的:
String.prototype.ucFirst = function (mode = 'eachWord') {
const modes = {
eachWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g,
firstWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstChar: /^[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstLetter: /[A-Za-zÀ-ÖØ-öø-ÿ]/,
};
if (mode in modes) {
return this.replace(modes[mode], c => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: ` + Object.keys(modes).join('|');
}
};
console.log('eachWord', 'foO bAr'.ucFirst());
// FoO BAr
console.log('eachWord', 'foO bAr'.toLowerCase().ucFirst());
// Foo Bar
console.log('firstWord', '1foO bAr'.ucFirst('firstWord'));
// 1foO BAr
console.log('firstChar', '1foO bAr'.ucFirst('firstChar'));
// 1foO bAr
console.log('firstLetter', '1foO bAr'.ucFirst('firstLetter'));
// 1FoO bAr
编辑:
或基于 String.prototype
处理多种模式的方法和一个可选的第二个参数来指定单词分隔符(String
或 RegExp
):
String.prototype.ucFirst = function (mode = 'eachWord', wordSeparator = /\s/) {
const letters = /[A-Za-zÀ-ÖØ-öø-ÿ]/;
const ws =
'^|' +
(wordSeparator instanceof RegExp
? '(' + wordSeparator.source + ')'
: // sanitize string for RegExp
'[' + wordSeparator.replace(/[[{}()*+?^$|\]\.\]/g, '\$&') + ']');
const r =
mode === 'firstLetter'
? letters
: mode === 'firstChar'
? new RegExp('^' + letters.source)
: mode === 'firstWord' || mode === 'eachWord'
? new RegExp(
'(' + ws + ')' + letters.source,
mode === 'eachWord' ? 'g' : undefined
)
: undefined;
if (r) {
return this.replace(r, (c) => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: firstLetter|firstChar|firstWord|eachWord`;
}
};
console.log("mike o'hara".ucFirst('eachWord', " \t\r\n\f\v'"));
// Mike O'Hara
console.log("mike o'hara".ucFirst('eachWord', /[\s']/));
// Mike O'Hara
var str = "hello world"
var result = str.split(" ").map(element => {
return element[0].toUpperCase() + element.slice(1);
});
result = result.join(" ")
console.log(result);
试试这个函数:
const capitializeName = (name) => {
const splitName = name.split(' ');
const namesUpper = [];
for (const n of splitName) {
namesUpper.push(n[0].toUpperCase() + n.slice(1));
}
console.log(namesUpper.join(' '));
};
capitializeName('jahid bhuiyan');
您可以以此为基础 inputString[0].toUpperCase() + inputString.slice(1).toLowerCase()
:)
我正在尝试编写一个将字符串中每个单词的首字母大写的函数(将字符串转换为首字母大写)。
例如,当输入为 "I'm a little tea pot"
时,我希望输出为 "I'm A Little Tea Pot"
。但是,函数 returns "i'm a little tea pot"
.
这是我的代码:
function titleCase(str) {
var splitStr = str.toLowerCase().split(" ");
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(" ");
}
return str;
}
console.log(titleCase("I'm a little tea pot"));
你把复杂的事情变得很简单了。您可以将此添加到 CSS:
.capitalize {
text-transform: capitalize;
}
在 JavaScript 中,您可以将 class 添加到元素
document.getElementById("element").className = "capitalize";
您没有再次将您的更改分配给数组,所以您所有的努力都是徒劳的。试试这个:
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
此例程将处理带连字符的单词和带撇号的单词。
function titleCase(txt) {
var firstLtr = 0;
for (var i = 0;i < text.length;i++) {
if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
if (text.charAt(i) == "'") {
if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1)))
firstLtr = 3;
else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2)))
firstLtr = 3;
}
if (firstLtr == 3)
firstLtr = 1;
else
firstLtr = 0;
}
if (firstLtr == 2) {
firstLtr = 1;
text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
}
else {
text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
}
}
}
titleCase("pAt o'Neil's");
// returns "Pat O'Neil's";
function titleCase(str) {
var myString = str.toLowerCase().split(' ');
for (var i = 0; i < myString.length; i++) {
var subString = myString[i].split('');
for (var j = 0; j < subString.length; j++) {
subString[0] = subString[0].toUpperCase();
}
myString[i] = subString.join('');
}
return myString.join(' ');
}
ECMAScript 6版本:
title
.split(/ /g).map(word =>
`${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
.join(" ");
如果您可以使用第三方库,那么 Lodash 可以为您提供辅助功能。
https://lodash.com/docs/4.17.3#startCase
_.startCase('foo bar');
// => 'Foo Bar'
_.startCase('--foo-bar--');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
/* 1. Transform your string into lower case
2. Split your string into an array. Notice the white space I'm using for the separator
3. Iterate the new array, and assign the current iteration value (array[c]) a new formatted string:
- With the sentence: array[c][0].toUpperCase() the first letter of the string converts to upper case.
- With the sentence: array[c].substring(1) we get the rest of the string (from the second letter index to the last one).
- The "add" (+) character is for concatenate both strings.
4. return array.join(' ') // Returns the formatted array like a new string. */
function titleCase(str){
str = str.toLowerCase();
var array = str.split(' ');
for(var c = 0; c < array.length; c++){
array[c] = array[c][0].toUpperCase() + array[c].substring(1);
}
return array.join(' ');
}
titleCase("I'm a little tea pot");
ECMAScript 6版本:
const toTitleCase = (phrase) => {
return phrase
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);
原始代码:
function capi(str) {
var s2 = str.trim().toLowerCase().split(' ');
var s3 = [];
s2.forEach(function(elem, i) {
s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
});
return s3.join(' ');
}
capi('JavaScript string exasd');
我用了 replace()
和正则表达式:
function titleCase(str) {
var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());
console.log(newStr);
}
titleCase("I'm a little tea pot")
也是一个不错的选择(特别是如果您使用 freeCodeCamp):
function titleCase(str) {
var wordsArray = str.toLowerCase().split(/\s+/);
var upperCased = wordsArray.map(function(word) {
return word.charAt(0).toUpperCase() + word.substr(1);
});
return upperCased.join(" ");
}
或者可以使用 replace() 来完成,将每个单词的第一个字母替换为它的“大写”。
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
titleCase("I'm a little tea pot");
-
您可以简单地使用正则表达式函数来更改每个字母的大小写。通过 V8 JIST 优化,这应该被证明是快速和内存高效的。
// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})
或者,作为函数:
// Only works for Latin-I strings
var fromCharCode = String.fromCharCode;
var firstLetterOfWordRegExp = /\b[a-z]|['_][a-z]|\B[A-Z]/g;
function toLatin1UpperCase(x){ // avoid frequent anonymous inline functions
var charCode = x.charCodeAt(0);
return charCode===39 ? x : fromCharCode(charCode^32);
}
function titleCase(string){
return string.replace(firstLetterOfWordRegExp, toLatin1UpperCase);
}
根据 this benchmark,代码比 Chrome 中的下一个最佳解决方案快 33% 以上。
<textarea id="input" type="text">I'm a little tea pot</textarea><br /><br />
<textarea id="output" type="text" readonly=""></textarea>
<script>
(function(){
"use strict"
var fromCode = String.fromCharCode;
function upper(x){return x[0]==="'"?x:fromCode(x.charCodeAt(0) ^ 32)}
(input.oninput = function(){
output.value = input.value.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, upper);
})();
})();
</script>
请检查下面的代码。
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
var nstr = "";
for (var i = 0; i < splitStr.length; i++) {
nstr += (splitStr[i].charAt(0).toUpperCase()+ splitStr[i].slice(1) + "
");
}
console.log(nstr);
}
var strng = "this is a new demo for checking the string";
titleCase(strng);
由于可读性,我通常不喜欢使用正则表达式,而且我尽量避免循环。我认为这有点可读性。
function capitalizeFirstLetter(string) {
return string && string.charAt(0).toUpperCase() + string.substring(1);
};
@somethingthere 提出的解决方案的更紧凑(和现代)重写:
let titleCase = (str => str.toLowerCase().split(' ').map(
c => c.charAt(0).toUpperCase() + c.substring(1)).join(' '));
document.write(titleCase("I'm an even smaller tea pot"));
自 ECMA2017 或 ES8 起
const titleCase = (string) => {
return string
.split(' ')
.map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length))
.join(' ');
};
let result = titleCase('test test test');
console.log(result);
解释:
1. 首先,我们将字符串 "test test test" 传递给我们的函数 "titleCase".
2. 我们在 space 基础上拆分字符串,因此第一个函数 "split" 的结果将是 ["test","test","test"]
3. 当我们得到一个数组时,我们使用 map 函数来操作数组中的每个单词。我们将第一个字符大写并向其添加剩余字符。
4. 最后,我们使用 space 连接数组,因为我们按 sapce 拆分字符串。
这是使用 map
函数的基本方法,它与公认的答案相同,但没有 for-loop
。因此,为您节省几行代码。
function titleCase(text) {
if (!text) return text;
if (typeof text !== 'string') throw "invalid argument";
return text.toLowerCase().split(' ').map(value => {
return value.charAt(0).toUpperCase() + value.substring(1);
}).join(' ');
}
console.log(titleCase("I'm A little tea pot"));
除了尝试将所有单词的所有首字母(即通过正则表达式定义 \w+
)转换为大写外,下面的函数不会更改字符串的任何其他部分。
这意味着它 不一定 将单词转换为 Titlecase,但确实如问题标题所述:"Capitalize First Letter Of Each Word In A String - JavaScript"
- 不要拆分字符串
- 通过等同于
[A-Za-z0-9_]+
的正则表达式\w+
确定每个 word- 仅将函数
String.prototype.toUpperCase()
应用于每个单词的第一个字符。
- 仅将函数
function first_char_to_uppercase(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
});
}
示例:
first_char_to_uppercase("I'm a little tea pot");
// "I'M A Little Tea Pot"
// This may look wrong to you, but was the intended result for me
// You may wanna extend the regex to get the result you desire, e.g., /[\w']+/
first_char_to_uppercase("maRy hAd a lIttLe LaMb");
// "MaRy HAd A LIttLe LaMb"
// Again, it does not convert words to Titlecase
first_char_to_uppercase(
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
// "ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples"
first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
// "…N1=OrangesFromSPAIN&&N2!='A Sub-String Inside'"
first_char_to_uppercase("snake_case_example_.Train-case-example…");
// "Snake_case_example_.Train-Case-Example…"
// Note that underscore _ is part of the RegEx \w+
first_char_to_uppercase(
"Capitalize First Letter of each word in a String - JavaScript"
);
// "Capitalize First Letter Of Each Word In A String - JavaScript"
编辑 2019-02-07:如果你想要实际的 Titlecase(即只有第一个字母大写,所有其他字母小写):
function titlecase_all_words(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});
}
显示两者的示例:
test_phrases = [
"I'm a little tea pot",
"maRy hAd a lIttLe LaMb",
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
"…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
"snake_case_example_.Train-case-example…",
"Capitalize First Letter of each word in a String - JavaScript"
];
for (el in test_phrases) {
let phrase = test_phrases[el];
console.log(
phrase,
"<- input phrase\n",
first_char_to_uppercase(phrase),
"<- first_char_to_uppercase\n",
titlecase_all_words(phrase),
"<- titlecase_all_words\n "
);
}
// I'm a little tea pot <- input phrase
// I'M A Little Tea Pot <- first_char_to_uppercase
// I'M A Little Tea Pot <- titlecase_all_words
// maRy hAd a lIttLe LaMb <- input phrase
// MaRy HAd A LIttLe LaMb <- first_char_to_uppercase
// Mary Had A Little Lamb <- titlecase_all_words
// ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples <- input phrase
// ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples <- first_char_to_uppercase
// Examplex: Camelcase/Uppercase&Lowercase,Exampley:N0=Apples <- titlecase_all_words
// …n1=orangesFromSPAIN&&n2!='a sub-string inside' <- input phrase
// …N1=OrangesFromSPAIN&&N2!='A Sub-String Inside' <- first_char_to_uppercase
// …N1=Orangesfromspain&&N2!='A Sub-String Inside' <- titlecase_all_words
// snake_case_example_.Train-case-example… <- input phrase
// Snake_case_example_.Train-Case-Example… <- first_char_to_uppercase
// Snake_case_example_.Train-Case-Example… <- titlecase_all_words
// Capitalize First Letter of each word in a String - JavaScript <- input phrase
// Capitalize First Letter Of Each Word In A String - JavaScript <- first_char_to_uppercase
// Capitalize First Letter Of Each Word In A String - Javascript <- titlecase_all_words
text-transform: capitalize;
CSS 知道了:)
在 ECMAScript 6 中,使用箭头函数的单行答案:
const captialize = words => words.split(' ').map( w => w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')
function LetterCapitalize(str) {
return str.split(" ").map(item=>item.substring(0,1).toUpperCase()+item.substring(1)).join(" ")
}
下面是另一种将字符串中每个单词的第一个字母大写的方法。
使用 prototype
.
String.prototype.capitalize = function() {
var c = '';
var s = this.split(' ');
for (var i = 0; i < s.length; i++) {
c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
}
return c;
}
var name = "john doe";
document.write(name.capitalize());
let cap = (str) => {
let arr = str.split(' ');
arr.forEach(function(item, index) {
arr[index] = item.replace(item[0], item[0].toUpperCase());
});
return arr.join(' ');
};
console.log(cap("I'm a little tea pot"));
快速可读版本参见基准测试http://jsben.ch/k3JVz
我觉得这样应该会更快;因为它不会拆分字符串并再次加入它;仅使用正则表达式。
var str = text.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
解释:
(^\w{1})
: 匹配字符串的第一个字符|
: 或(\s{1}\w{1})
:匹配一个 space 之后的一个字符
g
:匹配全部- match => match.toUpperCase(): 替换为可以带函数,所以;用大写匹配替换匹配
function titleCase(str) {
//First of all, lets make all the characters lower case
let lowerCaseString = "";
for (let i = 0; i < str.length; i++) {
lowerCaseString = lowerCaseString + str[i].toLowerCase();
}
//Now lets make the first character in the string and the character after the empty character upper case and leave therest as it is
let i = 0;
let upperCaseString = "";
while (i < lowerCaseString.length) {
if (i == 0) {
upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase();
} else if (lowerCaseString[i - 1] == " ") {
upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase();
} else {
upperCaseString = upperCaseString + lowerCaseString[i];
}
i = i + 1;
}
console.log(upperCaseString);
return upperCaseString;
}
titleCase("hello woRLD");
这里有一个完整而简单的解决方案:
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index
+ replacement.length);
}
var str = 'k j g u i l p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
for(let i = 0; i < str.length-1; i++) {
if(str[i] === ' ' && str[i+1] !== '')
str = str.replaceAt(i+1, str[i+1].toUpperCase());
}
return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));
ES6 语法
const captilizeAllWords = (sentence) => {
if (typeof sentence !== "string") return sentence;
return sentence.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
captilizeAllWords('Something is going on here')
最短的一行(也极快):
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
解释:
^\w
: 字符串的第一个字符|
: 或\s\w
: 空格后的第一个字符(^\w|\s\w)
捕获模式。g
标记:匹配所有匹配项。
如果您想确保其余部分是小写:
text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
用法示例:
const toTitleCase = str => str.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
console.log(toTitleCase("heLLo worLd"));
这里我使用了三个函数toLowerCase()
、toUpperCase()
和replace(regex,replacer)
function titleCase(str) {
return str.toLowerCase().replace(/^(\w)|\s(\w)/g, (grp) => grp.toUpperCase());
}
titleCase("I'm a little tea pot");
这是一种简单的转换方法,能够传递一个值以获得所需的输出。
String.prototype.toChangeCase = function (type) {
switch (type) {
case 'upper-first':
return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
case 'upper-each':
return this.split(' ').map(word => {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
}).join(' ');
default:
throw Error(`In order to get the output pass a value 'upper-first', 'upper-each'`);
}
}
产出
"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-first')
"Capitalize first letter of each word in a sstring"
"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-each')
"Capitalize First Letter Of Each Word In A Sstring"
"Capitalize First Letter Of Each Word In A String".toChangeCase()
VM380:12 Uncaught Error: In order to get the output pass a value 'upper-first', 'upper-each'
at String.toChangeCase (<anonymous>:12:19)
at <anonymous>:16:52
这里我使用了replace()
函数
function titleCase(str){
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
您可以使用现代 JS 语法,让您的生活更轻松。这是我针对给定问题的代码片段:
const capitalizeString = string => string.split(' ').map(item => item.replace(item.charAt(0), item.charAt(0).toUpperCase())).join(' ');
capitalizeString('Hi! i am aditya shrivastwa')
let string = "I'm a little tea pot";
现在,创建一个将字符串作为参数的函数。
function titleCase(str) {
return str.split(" ").map(s => s.charAt(0).toUpperCase() + s.substr(1).toLowerCase()).join(" ")
}
输出
titleCase(string); // "I'm A Little Tea Pot"
你可以用这样简单的方式在一行中使用带有 toUpperCase 的 map:
text.split(' ').map(w => { let t = w.split(''); t[0] = t[0].toUpperCase(); return t.join('') }).join(' ')
TypeScript 粗箭头 FTW
export const formatTitleCase = (string: string) =>
string
.toLowerCase()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.substring(1))
.join(" ");
我已经使用下面的代码完成了此操作,希望对您有所帮助:
<p id="p1">This is a paragraph.</p>
<script>
const capitalize = (mySentence) => {
const words = mySentence.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join(" ");
};
const result = capitalize('This is a sample text');
document.getElementById("p1").innerHTML = result;
</script>
这里是简单的一行
const ucFirst = t => t.replace(/(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g, c => c.toUpperCase());
注意它只改变每个单词首字母的大小写,你可能想这样使用它:
console.log(ucFirst('foO bAr'));
// FoO BAr
console.log(ucFirst('foO bAr'.toLowerCase()));
// Foo Bar
// works with accents too
console.log(ucFirst('éfoO bAr'));
// ÉfoO BAr
或者基于String.prototype
,这里有一个可以处理多种模式的:
String.prototype.ucFirst = function (mode = 'eachWord') {
const modes = {
eachWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g,
firstWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstChar: /^[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstLetter: /[A-Za-zÀ-ÖØ-öø-ÿ]/,
};
if (mode in modes) {
return this.replace(modes[mode], c => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: ` + Object.keys(modes).join('|');
}
};
console.log('eachWord', 'foO bAr'.ucFirst());
// FoO BAr
console.log('eachWord', 'foO bAr'.toLowerCase().ucFirst());
// Foo Bar
console.log('firstWord', '1foO bAr'.ucFirst('firstWord'));
// 1foO BAr
console.log('firstChar', '1foO bAr'.ucFirst('firstChar'));
// 1foO bAr
console.log('firstLetter', '1foO bAr'.ucFirst('firstLetter'));
// 1FoO bAr
编辑:
或基于 String.prototype
处理多种模式的方法和一个可选的第二个参数来指定单词分隔符(String
或 RegExp
):
String.prototype.ucFirst = function (mode = 'eachWord', wordSeparator = /\s/) {
const letters = /[A-Za-zÀ-ÖØ-öø-ÿ]/;
const ws =
'^|' +
(wordSeparator instanceof RegExp
? '(' + wordSeparator.source + ')'
: // sanitize string for RegExp
'[' + wordSeparator.replace(/[[{}()*+?^$|\]\.\]/g, '\$&') + ']');
const r =
mode === 'firstLetter'
? letters
: mode === 'firstChar'
? new RegExp('^' + letters.source)
: mode === 'firstWord' || mode === 'eachWord'
? new RegExp(
'(' + ws + ')' + letters.source,
mode === 'eachWord' ? 'g' : undefined
)
: undefined;
if (r) {
return this.replace(r, (c) => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: firstLetter|firstChar|firstWord|eachWord`;
}
};
console.log("mike o'hara".ucFirst('eachWord', " \t\r\n\f\v'"));
// Mike O'Hara
console.log("mike o'hara".ucFirst('eachWord', /[\s']/));
// Mike O'Hara
var str = "hello world"
var result = str.split(" ").map(element => {
return element[0].toUpperCase() + element.slice(1);
});
result = result.join(" ")
console.log(result);
试试这个函数:
const capitializeName = (name) => {
const splitName = name.split(' ');
const namesUpper = [];
for (const n of splitName) {
namesUpper.push(n[0].toUpperCase() + n.slice(1));
}
console.log(namesUpper.join(' '));
};
capitializeName('jahid bhuiyan');
您可以以此为基础 inputString[0].toUpperCase() + inputString.slice(1).toLowerCase()
:)