提问人:Robert Wills 提问时间:6/22/2009 最后编辑:miken32Robert Wills 更新时间:11/15/2023 访问量:3917008
如何在 JavaScript 中使字符串的第一个字母大写?
How do I make the first letter of a string uppercase in JavaScript?
问:
如果字符串是字母,如何使字符串的第一个字符大写,但不更改任何其他字母的大小写?
例如:
"this is a test"
→"This is a test"
"the Eiffel Tower"
→"The Eiffel Tower"
"/index.html"
→"/index.html"
答:
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
其他一些答案会修改(这个答案也曾经修改过),但由于可维护性,我现在建议不要这样做(很难找出将函数添加到何处,如果其他代码使用相同的名称/浏览器将来添加具有相同名称的本机函数,则可能会导致冲突)。String.prototype
prototype
评论
string
const capitalize = <T extends string>(s: T) => (s[0].toUpperCase() + s.slice(1)) as Capitalize<typeof s>;
charAt
"flat"
"FLat"
这是一个名为(“大写首字母”的缩写)的函数:ucfirst()
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
您可以通过调用 -- 例如,ucfirst("some string")
ucfirst("this is a test") --> "This is a test"
它的工作原理是将字符串分成两部分。在第一行上,它拉出,然后在第二行上,它通过调用将其大写并将其与字符串的其余部分连接起来,该字符串通过调用找到。firstLetter
firstLetter
firstLetter.toUpperCase()
str.substr(1)
你可能会认为这对于一个空字符串来说会失败,事实上,在像 C 这样的语言中,你必须满足这一点。但是,在 JavaScript 中,当您获取空字符串的子字符串时,您只会返回一个空字符串。
评论
substr()
可能不会被任何流行的 ECMAScript 实现标记为弃用(我怀疑它不会很快消失),但它不是 ECMAScript 规范的一部分。该规范的第 3 版在非规范性附件中提到了它,以便“为这些属性提出统一的语义,而不会使属性或其语义成为本标准的一部分”。
substring
substr
slice
slice
slice
编辑添加此免责声明:请阅读评论以了解编辑 JS 基本类型的风险。
下面是一个更面向对象的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
您可以调用该函数,如下所示:
"hello, world!".capitalize();
预期输出为:
"Hello, world!"
评论
如果你这样做,该函数就会起作用。ucfirst
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
感谢 J-P 的声明。
评论
string[0].toUpperCase() + string.substring(1)
String.prototype.capitalize = function(){
return this.replace(/(^|\s)([a-z])/g,
function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
用法:
capitalizedString = someString.capitalize();
这是一个文本字符串 => 这是一个文本字符串
评论
return.this.toLocaleLowerCase().replace(
String.prototype.capitalize = function(){ return this.replace( /(^|\s)[a-z]/g , function(m){ return m.toUpperCase(); }); };
我稍微重构了你的代码,你只需要第一个匹配项。
如果您使用正则表达式答案之一,请记住它们仅适用于 ASCII 字符。您的所有 Unicode 字母都不会大写。如果您想坚持使用正则表达式,XRegExp 库及其 unicode 插件可以解决这个问题。所以像这样的东西会起作用:
String.prototype.capitalize = function () {
return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}
考虑到它仍然没有涵盖所有的可能性(组合字符,参见 http://www.regular-expressions.info/unicode.html),只使用 .charAt(0).toUpperCase() 方法似乎更容易。
评论
如果要重新格式化全大写文本,则可能需要修改其他示例,如下所示:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
这将确保更改以下文本:
TEST => Test
This Is A TeST => This is a test
评论
这是流行答案的缩短版本,通过将字符串视为数组来获取第一个字母:
function capitalize(s)
{
return s[0].toUpperCase() + s.slice(1);
}
更新
根据下面的评论,这在 IE 7 或更低版本中不起作用。
更新2:
为了避免空字符串(请参阅下面的 @njzk2 注释),您可以检查空字符串:undefined
function capitalize(s)
{
return s && s[0].toUpperCase() + s.slice(1);
}
ES6 版本
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)
// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""
评论
s ? s[0].toUpperCase() + s.slice(1) : ""
咖啡脚本
ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)
作为 String 原型方法:
String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
评论
将字符串中所有单词的首字母大写:
function ucFirstAllWords( str )
{
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ )
{
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
评论
s => s.split(' ').map(x => x[0].toUpperCase() + x.slice(1)).join(' ')
如果你可以把每个单词的首字母大写,并且你的用例是HTML的,你可以使用以下CSS:
<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>
这是来自 CSS text-transform 属性(在 W3Schools)。
评论
好的,所以我是 JavaScript 的新手。我无法让上述内容为我工作。于是我开始自己把它们放在一起。这是我的想法(关于相同、不同和有效的语法):
String name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
在这里,我从表单中获取变量(它也可以手动工作):
String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
输出:“我是聪明人......”;
评论
在 CSS 中:
p::first-letter {
text-transform:capitalize;
}
评论
::first-letter
display
block
inline-block
table-cell
list-item
table-caption
::first-letter
flex
grid
// Uppercase first letter
function ucfirst(field) {
field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}
用法:
<input type="text" onKeyup="ucfirst(this)" />
评论
field.value
在 CoffeeScript 中,将字符串添加到原型中:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
用法为:
"woobie".capitalize()
这产生:
"Woobie"
评论
String.prototype.capitalize = function () { return this.substring(0,1).toUpperCase() + this.substring(1).toLowerrCase() }
CoffeeScript is a little language that compiles into JavaScript.
The golden rule of CoffeeScript is: "It's just JavaScript."
一种可能的解决方案:
function ConvertFirstCharacterToUpperCase(text) {
return text.substr(0, 1).toUpperCase() + text.substr(1);
}
使用这个:
alert(ConvertFirstCharacterToUpperCase("this is string"));
这是工作 JS Fiddle
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
编辑:正则表达式对此大材小用,更喜欢更简单的:str.charAt(0).toUpperCase() + str.substring(1)
评论
我们可以得到第一个我最喜欢的角色之一,看起来像一个可爱的笑脸:RegExp
/^./
String.prototype.capitalize = function () {
return this.replace(/^./, function (match) {
return match.toUpperCase();
});
};
对于所有咖啡迷:
String::capitalize = ->
@replace /^./, (match) ->
match.toUpperCase()
...对于所有认为有更好的方法可以做到这一点的人,而无需扩展原生原型:
var capitalize = function (input) {
return input.replace(/^./, function (match) {
return match.toUpperCase();
});
};
评论
'Answer'.replace(/^./, v => v.toLowerCase())
对于另一种情况,我需要它将第一个字母大写并将其余字母小写。以下情况使我更改了此功能:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
该函数采用两个参数:
start - 起始索引;
length - 要大写的子字符串的长度
String.prototype.subUpper = function () {
var result = this.toString();
var start = 0;
var length = 1;
if (arguments.length > 0) {
start = arguments[0];
if (start < this.length) {
if (arguments.length > 1) {
length = arguments[1];
}
if (start + length > this.length) {
length = this.length - start;
}
var startRest = start + length;
var prefix = start > 0 ? this.substr(0, start) : String.empty;
var sub = this.substr(start, length);
var suffix = this.substr(startRest, this.length - startRest);
result = prefix + sub.toUpperCase() + suffix;
}
}
return result;
};
评论
String.prototype.capitalize = function(allWords) {
return (allWords) ? // If all words
this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
// calls until capitalizing all words
this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
// meaning the first character of the whole string
}
然后:
"capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
"capitalize all words".capitalize(true); ==> "Capitalize All Words"
2016 年 11 月更新 (ES6),只是为了好玩:
const capitalize = (string = '') => [...string].map( // Convert to array with each item is a char of
// string by using spread operator (...)
(char, index) => index ? char : char.toUpperCase() // Index true means not equal 0, so (!index) is
// the first character which is capitalized by
// the `toUpperCase()` method
).join('') // Return back to string
然后capitalize("hello") // Hello
评论
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
我一直在尝试使用jQuery做同样的事情(即,在输入字符串时将字符串中的第一个字母大写)。我在网上搜索了答案,但找不到。但是,我能够像这样使用jQuery中的函数来解决此问题:on()
$("#FirstNameField").on("keydown",function(e){
var str = $("#FirstNameField").val();
if(str.substring()===str.substring(0,1)){
$("#FirstNameField").val(str.substring(0,1).toUpperCase());
}
});
此函数实际上在数据输入者连续键入时将第一个字母大写。
这里有一些建议,可以制作一个通用函数,该函数只能将每个单词的第一个字母或第一个字母大写,包括用破折号或其他分隔符分隔的单词(如法语中的一些名字)。
默认情况下,该函数仅将整个字符串的第一个字母大写,其余字母保持不变。
参数:
- lc:true 强制将其余单词小写
- all: true 将每个单词大写
1. 无正则表达式版本
function capitalize( str, lc, all ) {
if( all ) {
return str.split( " " )
.map( word => capitalize( word, lc ) )
.join( " " )
.split( "-" )
.map( word => capitalize( word, false ) )
.join( "-" );
} else {
return lc
? str.charAt( 0 ).toUpperCase() + str.slice( 1 ).toLowerCase()
: str.charAt( 0 ).toUpperCase() + str.slice( 1 );
}
}
2.使用正则表达式
function capitalize( str, lc, all ) {
const replacer =
lc ? ( m, p1, p2 ) => p1.toUpperCase() + p2.toLowerCase()
: ( m, p1, p2 ) => p1.toUpperCase() + p2;
if( all ) {
return str.split( /(\s|-|')/ )
.map( s => s.replace( /^([A-Za-zÀ-ÖØ-öø-ÿ])(.*)$/, replacer ) )
.join( "" )
} else {
return str.replace( /^([A-Za-zÀ-ÖØ-öø-ÿ])(.*)$/, replacer )
}
}
3. 使用休息参数进行替代
function capitalizeWord( [first, ...rest], lc ) {
return first.toUpperCase() + ( lc ? rest.join("").toLowerCase() : rest.join("") );
}
function capitalize( str, lc, all ) {
return all ? str.split( /(\s|-|')/ )
.map( s => capitalizeWord( s, lc ) )
.join( "" )
: capitalizeWord( str, lc );
}
例子
capitalize( "saiNT-jEAn d'anGÉly", false, false )
// returns "SaiNT-jEAn d'anGÉly"
capitalize( "saiNT-jEAn d'anGÉly", false, true )
// returns "SaiNT-JEAn D'AnGÉly"
capitalize( "saiNT-jEAn d'anGÉly", true, false )
// returns "Saint-jean d'angély"
capitalize( "saiNT-jEAn d'anGÉly", true, true )
// returns "Saint-Jean D'Angély"
评论
或者你可以使用 Sugar.js capitalize()
例:
'hello'.capitalize() -> 'Hello'
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
如果您使用 Underscore.js 或 Lodash,underscore.string 库提供字符串扩展,包括大写:
_.capitalize(string) 将字符串的第一个字母转换为 大写。
例:
_.capitalize("foo bar") == "Foo bar"
评论
humanize
这是我的版本。我认为它很容易理解,也很优雅。
var str = "foo bar baz";
// Capitalize
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
// Returns "Foo Bar Baz"
// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"
这是我虔诚地使用的:
function capitalizeMe(str, force){
str = force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
var firstName = capitalizeMe($firstName.val());
评论
var s = capitalizeMe('some RANDOM string', true);
true
用:
var str = "ruby java";
console.log(str.charAt(0).toUpperCase() + str.substring(1));
它将输出到控制台。"Ruby java"
var capitalizeMe = "string not starting with capital"
用 substr 大写
var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);
我在开发环境中使用了类似这些内容,尤其是在使用 HTTP 等 API 时:
假设您有一个 HTTP 标头,您希望在其中将名称中的每个首字母大写,并在其组成单词之间添加连字符。您可以使用以下基本且简单的例程实现类似目的:
'access control allow origin'
.replace(/\b\w/g, function (match) {
return match.toUpperCase();
})
.split(' ')
.join('-');
// Output: 'Access-Control-Allow-Origin'
它可能不是目前最优雅、最吸引人的函数定义,但它确实可以完成工作。
function capitalize(string) {
return string.replace(/^./, Function.call.bind("".toUpperCase));
}
评论
^
.
目前投票的答案是正确的,但它在将第一个字符大写之前不会修剪或检查字符串的长度。
String.prototype.ucfirst = function(notrim) {
s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}
设置 notrim 参数以防止先修剪字符串:
'pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst(true) => ' pizza'
评论
发布对 @salim 答案的编辑,以包括区域设置字母转换。
var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);
评论
str = str.charAt(0).toLocaleUpperCase() + str.substr(1);
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'
评论
substr
substring
slice
看看这个解决方案:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
评论
stringVal.replace(/^./, stringVal[0].toUpperCase());
stringVal[0]
undefined
stringVal
.toUpperCase()
喜欢它:
function capitalize(string,a) {
var tempstr = string.toLowerCase();
if (a == false || a == undefined)
return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
else {
return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
}
}
capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!
capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!
https://jsfiddle.net/dgmLgv7b/
如果您对发布的几种不同方法的性能感兴趣:
以下是基于此 jsperf 测试的最快方法(从最快到最慢排序)。
如您所见,前两种方法在性能方面基本上是可比的,而更改方法在性能方面是迄今为止最慢的。String.prototype
// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
return string[0].toUpperCase() + string.slice(1);
}
// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
return string.replace(/^./, string[0].toUpperCase());
}
// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
评论
如果您已经(或正在考虑)使用 Lodash,解决方案很简单:
_.upperFirst('fred');
// => 'Fred'
_.upperFirst('FRED');
// => 'FRED'
_.capitalize('fred') //=> 'Fred'
请参阅他们的文档:https://lodash.com/docs#capitalize
_.camelCase('Foo Bar'); //=> 'fooBar'
https://lodash.com/docs/4.15.0#camelCase
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'
_.snakeCase('Foo Bar');
// => 'foo_bar'
Vanilla JavaScript 为第一个大写字母:
function upperCaseFirst(str){
return str.charAt(0).toUpperCase() + str.substring(1);
}
一句话:
'string'.replace(/(^[a-z])/,function (p) { return p.toUpperCase(); } )
评论
这将执行相同的操作:
var newStr = string.slice(0,1).toUpperCase() + string.slice(1);
评论
首先,我只是想弄清楚在这种情况下大写的含义。 “This String Is Capitalized” 可靠来源
从提供的示例中可以看出,这不是 OP 正在寻找的。它应该说的是“如何使字符串的第一个字母大写”(不大写字符串)
function ucfirst (str) {
return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}
解释
typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string
这将适用于任何参数或根本没有参数。
undefined === ""
"" === ""
"my string" === "My string"
null === "Null"
undefined === "";
false === "False"
0 === "0"
true === "True"
[] === ""
[true,0,"",false] === "True,0,,false"
只需将第一个字母大写并使字符串的其余部分小写:
function capitalize(str) {
var splittedEnter = str.split(" ");
var capitalized;
var capitalizedResult;
for (var i = 0 ; i < splittedEnter.length ; i++){
capitalized = splittedEnter[i].charAt(0).toUpperCase();
splittedEnter[i] = capitalized + splittedEnter[i].substr(1).toLowerCase();
}
return splittedEnter.join(" ");
}
capitalize("tHiS wiLL be alL CapiTaLiZED.");
结果将是:
这将全部大写。
function capitalizeEachWord(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
document.write(capitalizeEachWord('foo BAR God bAD'));
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
一个小小的改进 - titlecase 中的每个单词。
String.prototype.toTitleCase = function(){
return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}
var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!
评论
如果您的项目中有,请使用 .Lodash
upperFirst
function cap(input) {
return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
// For other sentences in the text
return match.toUpperCase();
}).replace(/^\W*\w/, function(match, capture) {
// For the first sentence in the text
return match.toUpperCase();
});;
}
var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
// Output: Hi, dear user. It is a simple test. See you later!
// Bye
评论
使用原型
String.prototype.capitalize = function () {
return this.charAt(0) + this.slice(1).toLowerCase();
}
或使用函数
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
仅限 CSS
如果转换仅在网页上显示时需要:
p::first-letter {
text-transform: uppercase;
}
- 尽管被称为“:
:first-letter
”,但它适用于第一个字符,即在字符串的情况下,此选择器将应用于并且不会大写。%a
%
a
- 在 IE9+ 或 IE5.5+ 中,它支持仅使用一个冒号 () 的旧表示法。
:first-letter
ES2015 单线
const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
言论
- 在我执行的基准测试中,和 之间没有显着差异。但是请注意,这将是一个空字符串,因此必须重写该函数以使用 “”,与替代方案相比,这太冗长了。
string.charAt(0)
string[0]
string[0]
undefined
string && string[0]
string.substring(1)
比 快。string.slice(1)
和之间的基准substring()
slice()
如今,差异相当小(自己运行测试):
- 21,580,613.15 ops/s ±1.6% for ,
substring()
- 21,096,394.34 ops/s ±1.8%(慢 2.24%)。
slice()
评论
首先使用CSS处理这些事情总是更好,一般来说,如果你可以使用CSS解决某些问题,那就先去做,然后尝试使用JavaScript来解决你的问题,所以在这种情况下,尝试在CSS中使用并应用:first-letter
text-transform:capitalize;
因此,请尝试为此创建一个类,以便您可以全局使用它,例如: 并在 CSS 中添加如下内容:.first-letter-uppercase
.first-letter-uppercase:first-letter {
text-transform:capitalize;
}
另外,替代选项是 JavaScript,所以最好的是这样的:
function capitalizeTxt(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}
并这样称呼它:
capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html'); // return '/index.html'
capitalizeTxt('alireza'); // return 'Alireza'
capitalizeTxt('dezfoolian'); // return 'Dezfoolian'
如果你想一遍又一遍地重用它,最好把它附加到 javascript 原生字符串上,所以如下图所示:
String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
并按如下方式调用它:
'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt(); // return '/index.html'
'alireza'.capitalizeTxt(); // return 'Alireza'
适用于所有 Unicode 字符的解决方案
57 这个问题有 81 个不同的答案,有些偏离了主题,但它们都没有提出一个重要问题,即列出的解决方案都不适用于许多浏览器中的亚洲字符、表情符号和其他高 Unicode 点值字符。这是一个解决方案,它将:
const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toUpperCase() + S.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toUpperCase() + S.substring(2) :
S.charAt(0).toUpperCase() + S.substring(1)
);
};
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toLocaleUpperCase() + S.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toLocaleUpperCase() + S.substring(2) :
S.charAt(0).toLocaleUpperCase() + S.substring(1)
);
};
请注意,上述解决方案试图考虑 UTF-32。但是,该规范正式指出,浏览器需要以映射到 UCS2 的 UTF-16 执行所有操作。尽管如此,如果我们齐心协力,尽自己的一份力量,开始为 UTF32 做准备,那么 TC39 有可能允许浏览器开始使用 UTF-32(就像 Python 对字符串的每个字符使用 24 位一样)。对于说英语的人来说,这似乎很愚蠢:没有一个只使用拉丁语-1的人不得不处理Mojibake,因为拉丁语-I被所有字符编码所支持。但是,其他国家(如中国、日本、印度尼西亚等)的用户就没有那么幸运了。他们不仅在网页上,而且在JavaScript中都经常遇到编码问题:许多中文/日文字符被JavaScript视为两个字母,因此可能会在中间被拆分,从而导致和(两个问号对最终用户没有意义)。如果我们能开始为 UTF-32 做好准备,那么 TC39 可能只允许浏览器做 Python 多年前所做的事,这使得 Python 在处理高 Unicode 字符时非常流行:使用 UTF-32。
consistantCapitalizeFirstLetter
在 Internet Explorer 3+ 中正常工作(当 更改为 时)。 需要 Internet Explorer 5.5+(请参阅本文档第 250 页的顶部)。然而,这些事实更像是笑话,因为网页上的其余代码很可能甚至无法在 Internet Explorer 8 中工作 - 因为这些旧浏览器中存在所有 DOM 和 JScript 错误以及缺乏功能。此外,没有人再使用 Internet Explorer 3 或 Internet Explorer 5.5。const
var
prettyCapitalizeFirstLetter
评论
String.fromCodePoint(65536).length === 1
S
string
此解决方案可能是新的,也可能是最简单的。
function firstUpperCase(input)
{
return input[0].toUpperCase() + input.substr(1);
}
console.log(firstUpperCase("capitalize first letter"));
另一种使用 RamdaJs 的方法,即函数式编程方式:
firstCapital(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return fn(str);
}
字符串中有多个单词:
firstCapitalAllWords(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return R.map(fn,R.split(' ', str)).join(' ');
}
然而,仅仅因为你可以,并不意味着你应该这样做。它需要 ECMAScript 6,因为代码使用数组解构。
const capitalizeFirstLetter = s => {
const type = typeof s;
if (type !== "string") {
throw new Error(`Expected string, instead received ${type}`);
}
const [firstChar, ...remainingChars] = s;
return [firstChar.toUpperCase(), ...remainingChars].join("");
};
你可以像这样在一行中完成
string[0].toUpperCase() + string.substring(1)
评论
一行(“inputString 可以设置为任何字符串”):
inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())
评论
/.{1}/
NaN
0
这是 2018 ECMAScript 6+ 解决方案:
const str = 'the Eiffel Tower';
const newStr = `${str[0].toUpperCase()}${str.slice(1)}`;
console.log('Original String:', str); // the Eiffel Tower
console.log('New String:', newStr); // The Eiffel Tower
这是漂亮而干净的版本;
var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());
结果:
这是一个测试 --> 这是一个测试
这个很简单
const upper = lower.replace(/^\w/, c => c.toUpperCase());
yourString.replace(/\w/, c => c.toUpperCase())
我发现这个箭头功能最简单。Replace 匹配字符串的第一个字母字符 () 并将其转换为大写。没有什么比这更花哨的了。\w
评论
/./
/\w/
\w Matches any alphanumeric character from the basic Latin alphabet, including the underscore.
_boss
_boss
)
1boss
[A-Za-z-0-9]
[^\W_]
s[0].toUpperCase``+s.substr`1`
let s = 'hello there'
console.log( s[0].toUpperCase``+s.substr`1` )
功能方法
const capitalize = ([s, ...tring]) =>
[s.toUpperCase(), ...tring]
.join('');
然后你可以
const titleCase = str =>
str
.split(' ')
.map(capitalize)
.join(' ')
评论
最短的 3 个解决方案,1 和 2 处理字符串为 时的情况,并且:s
""
null
undefined
s&&s[0].toUpperCase()+s.slice(1) // 32 char
s&&s.replace(/./,s[0].toUpperCase()) // 36 char - using regexp
'foo'.replace(/./,x=>x.toUpperCase()) // 31 char - direct on string, ES6
let s='foo bar';
console.log( s&&s[0].toUpperCase()+s.slice(1) );
console.log( s&&s.replace(/./,s[0].toUpperCase()) );
console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );
有一种非常简单的方法可以通过替换来实现它。对于 ECMAScript 6:
'foo'.replace(/^./, str => str.toUpperCase())
结果:
'Foo'
评论
/^[a-z]/i
.
在现有的答案中,我没有看到任何与星体位面代码点或国际化相关的问题的提及。“大写”在使用给定脚本的每种语言中的含义并不相同。
最初,我没有看到任何解决与星体平面代码点相关的问题的答案。有一个,但它有点被埋没了(就像这个一样,我猜!
隐藏问题的概述及其解决方法
大多数建议的函数如下所示:
function capitalizeFirstLetter(str) {
return str[0].toUpperCase() + str.slice(1);
}
但是,某些大小写字符不属于 BMP(基本多语言平面,代码点 U+0 到 U+FFFF)。例如,以以下 Deseret 文本为例:
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"); // "𐐶𐐲𐑌𐐼𐐲𐑉"
此处的第一个字符无法大写,因为字符串的数组索引属性不访问“字符”或代码点*。它们访问 UTF-16 代码单元。在切片时也是如此 - 索引值指向代码单元。
UTF-16 代码单元恰好是 1:1,USV 码位在两个范围内,U+0 到 U+D7FF 和 U+E000 到 U+FFFF(含)。大多数大小写字符都属于这两个范围,但不是全部。
从 ES2015 开始,处理这个问题变得更容易一些。 生成与代码点对应的字符串**。例如,我们可以这样做:String.prototype[@@iterator]
function capitalizeFirstLetter([ first='', ...rest ]) {
return [ first.toUpperCase(), ...rest ].join('');
}
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"
对于较长的字符串,这可能不是非常高效***——我们实际上不需要迭代其余部分。我们可以用它来获得第一个(可能的)字母,但我们仍然需要确定切片应该从哪里开始。避免迭代其余代码的一种方法是测试第一个代码点是否在 BMP 之外;如果不是,则切片从 1 开始,如果是,则切片从 2 开始。String.prototype.codePointAt
function capitalizeFirstLetter(str) {
if (!str) return '';
const firstCP = str.codePointAt(0);
const index = firstCP > 0xFFFF ? 2 : 1;
return String.fromCodePoint(firstCP).toUpperCase() + str.slice(index);
}
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"
你可以使用按位数学而不是> 0xFFFF
,但这样可能更容易理解,而且两者都能实现相同的目的。
如有必要,我们也可以在 ES5 及以下版本中进一步利用该逻辑来实现这一目标。ES5 中没有用于处理代码点的内部方法,因此我们必须手动测试第一个代码单元是否是代理项****:
function capitalizeFirstLetter(str) {
if (!str) return '';
var firstCodeUnit = str[0];
if (firstCodeUnit < '\uD800' || firstCodeUnit > '\uDFFF') {
return str[0].toUpperCase() + str.slice(1);
}
return str.slice(0, 2).toUpperCase() + str.slice(2);
}
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"
更深入地进行国际化(谁的资本化?
一开始,我还提到了国际化的考虑。其中一些很难解释,因为它们不仅需要了解正在使用的语言,而且还可能需要对语言中的单词有特定的了解。例如,爱尔兰语双字母“mb”在单词的开头大写为“mB”。另一个例子,德语 eszett,从不开始一个单词 (afaik),但仍然有助于说明问题。小写的 eszett (“ß”) 大写为“SS”,但“SS”可以小写为“ß”或“ss”——您需要带外德语知识才能知道哪个是正确的!
这类问题最著名的例子可能是土耳其语。在土耳其拉丁语中,i 的大写形式是 İ,而 I 的小写形式是 ı——它们是两个不同的字母。幸运的是,我们确实有一种方法可以解释这一点:
function capitalizeFirstLetter([ first='', ...rest ], locale) {
return [ first.toLocaleUpperCase(locale), ...rest ].join('');
}
capitalizeFirstLetter("italy", "en") // "Italy"
capitalizeFirstLetter("italya", "tr") // "İtalya"
在浏览器中,用户最喜欢的语言标签由 ,在 中找到按优先顺序排列的列表,并且给定的 DOM 元素的语言(通常)可以在多语言文档中获取。navigator.language
navigator.languages
Object(element.closest('[lang]')).lang || YOUR_DEFAULT_HERE
在 ES2018 中引入的 RegExp 中支持 Unicode 属性字符类的代理中,我们可以通过直接表达我们感兴趣的字符来进一步清理内容:
function capitalizeFirstLetter(str, locale=navigator.language) {
return str.replace(/^\p{CWU}/u, char => char.toLocaleUpperCase(locale));
}
这可以稍微调整一下,以至少在某些语言中以相当高的准确性处理字符串中的多个单词大写,尽管如果无论主要语言是什么,都很难完全避免外围情况。
or Changes_When_Uppercased 字符属性匹配所有代码点,这些代码点在缺少特定区域设置数据的一般情况下大写时会更改。您可能希望使用其他与大小写相关的有趣 Unicode 字符属性。这是一个很酷的探索区,但如果我们在这里列举它们,我们会持续一整天。不过,如果您不熟悉,这里有一些东西可以激发您的好奇心:是一个比(又名)更大的组 - Unicode 提供的此工具中的默认字符集比较可以方便地说明。(注意:并非所有您可以引用的东西都可以在 ES 正则表达式中找到,但您可能想要的大多数东西都是)。CWU
\p{Lower}
\p{LowercaseLetter}
\p{Ll}
JS中案例映射的替代方案(Firefox和CSS喜欢荷兰语!
如果具有唯一区域设置/语言/正字法大写规则的二元组恰好在 Unicode 中具有单个代码点“组合”表示形式,则即使在没有区域设置数据的情况下,这些也可用于明确大写期望。例如,我们可能更喜欢与荷兰语相关的组合 i-j 二合字母 ij / U+133,以确保大小写映射到大写的 IJ / U+132:
capitalizeFirstLetter('ijsselmeer'); // "IJsselmeer"
另一方面,预先编写的二元图和类似的二元图有时会被弃用(就像那个一样!),并且在互换文本中可能是不可取的,因为如果这不是人们在实践中输入序列的正常方式,那么潜在的复制粘贴麻烦。不幸的是,在没有预合成“提示”的情况下,明确的语言环境在这里无济于事(至少据我所知)。如果我们用普通的 + 拼写,即使我们明确指示为语言环境,也会产生错误的结果:ijsselmeer
i
j
capitalizeFirstLetter
nl
capitalizeFirstLetter('ijsselmeer', 'nl'); // "Ijsselmeer" :(
(我不完全确定是否存在一些此类行为归结为 ICU 数据可用性的情况——也许其他人可以说。
但是,如果转换的目的是在 Web 浏览器中显示文本内容,那么您有一个完全不同的选项,这可能是您最好的选择:利用 Web 平台的其他核心语言 HTML 和 CSS 的功能。有了 HTML 和 CSS,你就得到了一个(伪)声明式解决方案,它为用户代理留下了额外的空间来“智能”。JS API 需要在所有浏览器(通常)上具有可预测的结果,并且不能自由地尝试启发式方法。但是,用户代理本身只对其用户有义务,当输出是针对人类时,启发式解决方案是公平的。如果我们告诉它“这个文本是荷兰语,但请将其大写显示”,那么具体结果现在可能因浏览器而异,但它可能是每个浏览器所能做的最好的。我看看:lang=...
text-transform:...
<!DOCTYPE html>
<dl>
<dt>Untransformed
<dd>ijsselmeer
<dt>Capitalized with CSS and <code>lang=en</code>
<dd lang="en" style="text-transform: capitalize">ijsselmeer
<dt>Capitalized with CSS and <code>lang=nl</code>
<dd lang="nl" style="text-transform: capitalize">ijsselmeer
在撰写本文时,在 Chromium 中,英语和荷兰语行都显示为 — 所以它并不比 JS 好。但是在当前的Firefox中尝试一下!我们告诉浏览器包含荷兰语的元素将在那里正确呈现为 IJsselmeer。Ijsselmeer
这个解决方案是针对特定目的的(无论如何,它不会在 Node 中帮助你),但鉴于有些人可能没有意识到他们在谷歌上搜索错误的问题,我以前不提请注意它是愚蠢的。感谢@paul23在实践中澄清了更多关于IJ二合图的性质,并促使进一步调查!
截至 2021 年 1 月,所有主要引擎都实现了 Unicode 属性字符类功能,但根据您的目标支持范围,您可能还无法安全地使用它。最后一个引入支持的浏览器是Firefox(78;2020 年 6 月 30 日)。您可以使用 Kangax 兼容表检查是否支持此功能。Babel 可用于编译 RegExp 文本,其中包含对等效模式的属性引用,但没有它们,但请注意,生成的代码有时可能非常庞大。您可能不想这样做,除非您确定这种权衡对于您的用例是合理的。
问这个问题的人很可能不会关心 Deseret 大写或国际化。但是,了解这些问题是件好事,因为即使它们目前不是问题,您也很有可能最终会遇到它们。它们不是“边缘”情况,或者更确切地说,它们不是定义上的边缘情况——无论如何,在整个国家,大多数人都说土耳其语,将代码单元与代码点混为一谈是相当常见的错误来源(尤其是在表情符号方面)。字符串和语言都非常复杂!
* UTF-16 / UCS2 的码位也是 Unicode 码位,例如 U+D800 在技术上是一个码位,但这不是这里的“意思”......有点......虽然它变得非常模糊。但是,替代物绝对不是 USV(Unicode 标量值)。
** 虽然如果代理代码单元是“孤立的”——即不是逻辑对的一部分——你仍然可以在这里获得代理。
或。我还没有测试过。除非你已经确定大写是一个有意义的瓶颈,否则我可能不会担心——选择你认为最清晰和可读的内容。
这样的函数可能希望同时测试第一个和第二个代码单元,而不仅仅是第一个代码单元,因为第一个单元可能是孤立的代理项。例如,输入“\uD800x”将按原样将 X 大写,这可能是预期的,也可能不是预期的。
评论
toUpperCase
capitalizeFirstLetter('ijssel', 'nl-NL')
ij
ij
有多种方法可以做到这一点,请尝试以下一些方法
var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);
如果你对正则表达式很满意,你可以这样做:
var upper = lower.replace(/^\w/, function (chr) {
return chr.toUpperCase();
});
您甚至可以通过使用更现代的语法更进一步:
const upper = lower.replace(/^\w/, c => c.toUpperCase());
此外,这将处理示例中提到的负面情况,例如以特殊字符开头的单词,例如 .!@#$%^&*()}{{[];':",.<>/?
我更喜欢使用面向函数式编程的解决方案(映射数组):
Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');
最简单的解决方案是:
let yourSentence = 'it needs first letter upper case';
yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);
艺术
yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);
艺术
yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);
评论
该方法将采用一个值,然后将其拆分为一个字符串数组。
const firstLetterToUpperCase = value => {
return value.replace(
value.split("")["0"], // Split stirng and get the first letter
value
.split("")
["0"].toString()
.toUpperCase() // Split string and get the first letter to replace it with an uppercase value
);
};
评论
/*
* As terse as possible, assuming you're using ES version 6+
*/
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());
console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\
Unicode 和区域设置感知
使用当前语言功能:
function capitalize([firstLetter, ...rest]) {
return [firstLetter.toLocaleUpperCase(), ...rest].join('');
}
console.log(capitalize('foo bar'));
console.log(capitalize('ѷҥӕ'))
console.log(capitalize('🎁❄💊🎸⭐'));
// Title Case
console.log(
'Title Case:',
'foo bar'
.split(/\s+/)
.map(capitalize)
.join(' '),
);
我们接受一个解构字符串作为唯一的参数,将第一个字符分配给变量,并为绑定到变量的其余字符()获取一个数组。例如,对于字符串,这应该如下所示:[firstLetter, ...rest]
firstLetter
...rest
rest
lorem ipsum
capitalize('lorem ipsum');
// firstLetter = 'l'
// rest = ['o', 'r', 'e', 'm', ' ', 'i', 'p', 's', 'u', 'm'];
现在我们需要做的就是在数组前面加上第一个字母 firstLetter.toLocaleUpperCase()
的大写版本(使用 spread 运算符),并使用 .join('')
将生成的数组连接到一个字符串中rest
评论
使用JS替换字符串方法和带有单词边界的正则表达式似乎很简单。
将第一个单词的第一个字符大写:“埃菲尔铁塔”-->“埃菲尔铁塔”
str.replace(/\b\w/, v => v.toUpperCase())
将所有单词的第一个字符大写:“埃菲尔铁塔”-->“埃菲尔铁塔”
str.replace(/\b\w/g, v => v.toUpperCase())
第一个单词大写:最短
text.replace(/(^.)/, m => m.toUpperCase())
每个单词大写:最短
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
如果要确保其余部分为小写:
text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
评论
evence coppéeplaats
Evence Coppéeplaats
é
1. 我们将使用 CSS 来实现这一点。它也可以从外部CSS进行设置。
<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>
2. 使用普通的 JavaScript,我们可以:
let string = "test case"
string = string[0].toUpperCase() + string.substring(1)
//return "Test case"
说明</b/>:
string[0].toUpperCase()
:将字符串中的第一个字母转换为大写
string.substring(1)
:删除字符串中的第一个字母并返回剩余字符
text-transform="capitalize"
:将此标签中每个单词的首字母设为大写。如果使用“大写”作为 text-transform 的值,则标记中的每个字母都将是大写字母
任何类型的字符串都可以转换 --
YoUrStRiNg → Yourstring
var str = yOuRsTrING.toLowerCase(); // Output: yourstring
str.charAt(0).toUpperCase() + str.slice(1); // Output: Y + ourstring = Yourstring
只是因为这真的是一句话,所以我会包括这个答案。它是一个基于 ES6 的插值字符串单行代码。
let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
每个字符串的第一个字符都是大写的。
function capitalize(word){
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
console.log(capitalize("john")); //John
console.log(capitalize("BRAVO")); //Bravo
console.log(capitalize("BLAne")); //Blane
评论
我只使用正则表达式:
myString = ' the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());
如果需要所有单词都以大写字母开头,可以使用以下函数:
const capitalLetters = (s) => {
return s.trim().split(" ").map(i => i[0].toUpperCase() + i.substr(1)).reduce((ac, i) => `${ac} ${i}`);
}
例:
console.log(`result: ${capitalLetters("this is a test")}`)
// Result: "This Is A Test"
评论
已经有很多好的答案,但你也可以使用一个简单的CSS转换:
text-transform: capitalize;
div.text-capitalize {
text-transform: capitalize;
}
<h2>text-transform: capitalize:</h2>
<div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
评论
你可以做str.replace(str[0], str[0].toUpperCase())
请看这个例子:
let str = "hello WORLD"
let newStr = str.replace(str[0], str[0].toUpperCase())
console.log("str: ", str)
console.log("newStr: ", newStr)
只需安装并加载 Lodash:
import { capitalize } from "lodash";
capitalize('test') // Test
使用箭头函数:
const capitalize = string => string[0].toUpperCase() + string.slice(1)
使用验证将第一个字母大写
function capitalizeFirstLetter(str) {
return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}
测试
console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
评论
你应该这样做:
let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
我知道这是一个有很多答案的老问题,但这是我的快速片段。
const capitalize = (str) => str?.split('').map( (e, i) => i === 0 ? e.toUpperCase() : e ).join('')
评论
此代码还将处理字符串开头和结尾处的额外空格。
let val = ' this is test ';
val = val.trim();
val = val.charAt(0).toUpperCase() + val.slice(1);
console.log("Value => ", val);
带箭头功能
let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"
带箭头功能,另一种解决方案
let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"
使用 array 和 map()
let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]
您可以使用正则表达式方法:
str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());
将字符串的第一个字符大写和取消大写。
功能包括:
/** First Character uppercase */
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/** First Character lowercase */
function uncapitalize(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
示例1 “第一个字符大写”:
alert(capitalize("hello world"));
结果:世界您好
示例 2 “第一个字符小写”:
alert(uncapitalize("Hello World, today is sunny"));
结果:你好,世界,今天是晴天
编辑: 我喜欢这个:
yourString.replace(/(^[a-z])/i, (str, firstLetter) => firstLetter.toUpperCase())
评论
在某些情况下,此代码可能工作良好:
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
console.log(capitalizeFirstLetter('foo')); // Foo
// But if we had like this it won't work well
console.log(capitalizeFirstLetter('fOo')); // FOo
但是,如果你真的想确保,只有第一个字母大写,其余的都是由小写字母构成的,你可以像这样调整代码:
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
console.log(capitalizeFirstLetter('fOo')); // Foo
评论
解决方案
Cannot read property 'charAt' of undefined
const capitalize = (string) => {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : "";
}
console.log(capitalize("i am a programmer")); // I am a programmer
评论
带有模板字符串的简单 ES6 语法
const capitalize = (str) => {
return `${str[0].toUpperCase()}${str.slice(1)}`
// return str[0].toUpperCase() + str.slice(1) // without template string
}
console.log(capitalize("this is a test"));
console.log(capitalize("the Eiffel Tower"));
console.log(capitalize("/index.html"));
/*
"this is a test" → "This is a test"
"the Eiffel Tower" → "The Eiffel Tower"
"/index.html" → "/index.html"
*/
要将所有单词大写:
打字稿版本:
const capitalize = (str:string)=>{
// Split into words
const words = str.split(" ");
const resWords:string[] = [];
// loop over words, slicing and capitalizing the first letter of each word.
words.forEach(word => {
const letterOne = word.slice(0, 1);
const upperCaseLetterOne = letterOne.toUpperCase();
const otherLetters = word.slice(1);
const newWord = upperCaseLetterOne+otherLetters
resWords.push(newWord)
});
// Turn it back into a human-readable string.
return resWords.join(" ");
}
Javascript 版本:
const capitalize = (str)=>{
// Split into words
const words = str.split(" ");
const resWords = [];
// loop over words, slicing and capitalizing the first letter of each word.
words.forEach(word => {
const letterOne = word.slice(0, 1);
const upperCaseLetterOne = letterOne.toUpperCase();
const otherLetters = word.slice(1);
const newWord = upperCaseLetterOne+otherLetters
resWords.push(newWord)
});
// Turn it back into a human-readable string.
return resWords.join(" ");
}
你可以像这样使用它:
const bookTitle = "my awesome book";
const displayBookTitle = capitalize(bookTitle);
console.log(displayBookTitle) // My Awesome Book
将第一个单词大写:
打字稿:
const capitalize = (str:string)=>{
return str.charAt(0).toUpperCase() + str.slice(1)
}
Javascript的:
const capitalize = (str)=>{
return str.charAt(0).toUpperCase()+str.slice(1);
}
你这样使用它:
console.log(capitalize("foo bar")) // Foo bar
评论
在循环中:
function capitalizeFirstIterative(array) {
let res = [];
for (let index = 0; index < array.length; index++) {
const element = array[index];
res.push(element.charAt(0).toUpperCase() + element.slice(1));
}
return res;
}
递 归:
function capitalizeFirst (array) {
if (array.length === 1) {
return [array[0][0].toUpperCase() + array[0].substr(1)];
}
const res = capitalizeFirst(array.slice(0, -1));
const string = array.slice(array.length - 1)[0][0].toUpperCase() + array.slice(array.length-1)[0].substr(1);
res.push(string);
return res;
}
包括此答案,因为这是使用扩展运算符的单行答案。不像其他答案那样出色。但仍然在不修改原始字符串的情况下完成工作。
const [firstLetter, ...rest] = "hello world";
console.log(`${firstLetter.toUpperCase()}${rest.join('')}`);
评论
console.log(([firstLetter, ...rest] = "hello world", `${firstLetter.toUpperCase()}${rest.join('')}`))
试试这个单行修复
text[0].toUpperCase() + text.substring(1)
function getCapitalizedText(text) {
return text[0].toUpperCase() + text.substring(1)
}
我们可以通过传递文本来多次调用它“getCapitalizedText”。
// capitalize only first character of multi words
var cfc = (str,fs=' ',es=' ')=>{ //str = string, fs = first separator, es = end separator
var str = str.split(fs);
var str2=[];
str.find((item)=>{
const a = item.charAt(0).toUpperCase()+item.slice(1).toLowerCase();
str2.push(a);
});
return str2.join(es);
}
const str = "stRing1#sTRIng2#strING3";
console.log(cfc(str,'#','@')); // output: String1@String2@String3
console.log(cfc(str,'#',' ')); // output: String1 String2 String3
我没有看到任何其他答案提到 Intl.Segmenter
,它“支持区分区域设置的文本分割”——这意味着在处理由多个代码点组成的字符时,您可以可靠地识别第一个字符。在浏览器中依赖它的最大警告是缺乏Firefox支持,请参阅 https://caniuse.com/mdn-javascript_builtins_intl_segmenter_segment 和 https://bugzilla.mozilla.org/show_bug.cgi?id=1423593。
有关详细信息,请参阅如何从字符串中获取字符数组?
这里已经有很多很好的答案,所以我将只专注于按字符拆分。
使用以下测试字符串,该字符串由 9 个字符/15 个代码点/20 个代码单元组成:
const str = '🐅-👨👩👧-நி-깍-葛󠄀';
幼稚,分裂
str.split('');
// (20) ["\ud83d", '\udc05', '-', '\ud83d', '\udc68', '', '\ud83d', '\udc69', '', '\ud83d', '\udc67', '-', 'ந', 'ி', '-', '깍', '-', '葛', '\udb40', '\udd00']
稍微好一点,点差操作员
[...str]
// (15) ["🐅", '-', '👨', '', '👩', '', '👧', '-', 'ந', 'ி', '-', '깍', '-', '葛', '󠄀']
Intl.Segmenter(在支持的浏览器中)
[...new Intl.Segmenter().segment(str)].map((g) => g.segment);
// (9) ["🐅", '-', '👨👩👧', '-', 'நி', '-', '깍', '-', '葛󠄀']
graphemer 1.4.0
import Graphemer from 'graphemer';
const splitter = new Graphemer();
splitter.splitGraphemes(str);
// (9) ["🐅", '-', '👨👩👧', '-', 'நி', '-', '깍', '-', '葛󠄀']
洛达什 4.17.10
import _ from 'lodash';
_.split(str, '');
// (11) ["🐅", '-', '👨👩👧', '-', 'ந', 'ி', '-', '깍', '-', '葛', '󠄀']
fabric.js v6.0.0-beta10 graphemeSplit (内部函数)
import { graphemeSplit } from './fabric_graphemeSplit';
graphemeSplit(str);
// (15) ["🐅", '-', '👨', '', '👩', '', '👧', '-', 'ந', 'ி', '-', '깍', '-', '葛', '󠄀']
@formatjs Intl.Segmenter 11.4.2 polyfill
await import('@formatjs/intl-segmenter/polyfill-force');
[...new Intl.Segmenter().segment(str)].map((g) => g.segment);
// (9) ["🐅", '-', '👨👩👧', '-', 'நி', '-', '깍', '-', '葛󠄀']
可编辑的比较:https://stackblitz.com/edit/stackblitz-typescript-lrag9u?devToolsHeight=90&file=index.ts
注意:重要信息: UTF-8 使用可变长度编码,这意味着它支持单个字符最多 4 个字节,codePointAt(1) >> 7 表示 prv codePoint 也是一个 Char,codePointAt() >> 7 如果 codePointAt(1) >> 11,则表示我们得到了一个 2 字节的 utf 8 消息,所以 16 和 21 是 4 字节 utf-8 字符的指示符。所以 codePointAt(4) >> 21 === 0 表示它是一个 4 字节的 utf-8 字符。所有这些检查都成本高昂,因此对所有字符串长度最有效的方法是
const upperCaseFirstLatterUtf8 = (str) => {
const b = str.substr(0,4).normalize();
return b[0].toUpperCase() + b.substr(1) + str.substr(4);
}
upperCaseFirstLatterUtf8('\u006E\u0303me!')
这是处理 utf-8 字符的唯一正确方法,如前所述,它们获得了高达 4 位的可变长度,这使用规范化,这相对昂贵,但存档我们目标的唯一高性能方法,即使检查所有字符代码也不会更快。然后我们将剩余的字符和大写的第一个字母作为单个 utf-32 字符返回,因此它始终是 4 位并移位 7
评论