如何在JavaScript中将字符串的首字母大写?

如何使字符串的第一个字母大写,但不更改其他任何字母的大小写?

例如:

  • "this is a test" -> "This is a test"
  • "the Eiffel Tower" -> "The Eiffel Tower"
  • "/index.html" -> "/index.html"
猪猪GO2020/03/09 12:54:39

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)
猪猪GO2020/03/09 12:54:39
yourString.replace(/\w/, c => c.toUpperCase())

I found this arrow function easiest. Replace matches the first letter character (\w) of your string and converts it to uppercase. Nothing fancier necessary.

小胖十三2020/03/09 12:54:39

The ucfirst function works if you do it like this.

function ucfirst(str) {
    var firstLetter = str.slice(0,1);
    return firstLetter.toUpperCase() + str.substring(1);
}

Thanks J-P for the aclaration.

番长神奇2020/03/09 12:54:39
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(You may encapsulate it in a function or even add it to the String prototype if you use it frequently.)

小小小胖2020/03/09 12:54:39
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
神无宝儿达蒙2020/03/09 12:54:39
String.prototype.capitalize = function(){
    return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
    } );
};

Usage:

capitalizedString = someString.capitalize();

This is a text string => This Is A Text String

猴子Near2020/03/09 12:54:39

Here is a function called ucfirst() (short for "upper case first letter"):

function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}

You can capitalise a string by calling ucfirst("some string") -- for example,

ucfirst("this is a test") --> "This is a test"

It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).

You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in JavaScript, when you take a substring of an empty string, you just get an empty string back.

Tom老丝Pro2020/03/09 12:54:39

If you are wanting to reformat all-caps text, you might want to modify the other examples as such:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

This will ensure that the following text is changed:

TEST => Test
This Is A TeST => This is a test
十万个冷笑话2020/03/09 12:54:39
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
LEY蛋蛋Near2020/03/09 12:54:39

在CSS中似乎更容易:

<style type="text/css">
    p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>

这是来自CSS文本转换属性(位于W3Schools)。

凯樱2020/03/09 12:54:38

采用:

var str = "ruby java";

console.log(str.charAt(0).toUpperCase() + str.substring(1));

它将输出"Ruby java"到控制台。

十三LEY2020/03/09 12:54:38
String.prototype.capitalize = function(allWords) {
   return (allWords) ? // if all words
      this.split(' ').map(word => word.capitalize()).join(' ') : //break down phrase to words then  recursive calls until capitalizing all words
      this.charAt(0).toUpperCase() + this.slice(1); // if allWords is undefined , capitalize only the first word , mean the first char 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 char which is capitalized by `toUpperCase()` method
 ).join('')                                             //return back to string

然后 capitalize("hello") // Hello

JinJin宝儿2020/03/09 12:54:38

我们可以得到第一个我最喜欢的角色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();
  });
};
LJinJin2020/03/09 12:54:38

如果您使用underscore.jsLo-Dash,则underscore.string库提供字符串扩展名,包括大写:

_.capitalize(string)将字符串的首字母转换为大写。

例:

_.capitalize("foo bar") == "Foo bar"
前端Stafan2020/03/09 12:54:38

将字符串中所有单词的首字母大写:

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(" ");
}
YOC715882172020/03/09 12:54:38
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

修改了其他一些答案String.prototype(这个答案也曾经使用过),但是由于可维护性,我现在建议这样做(很难找出将函数添加到的位置prototype,如果其他代码使用相同的名称/浏览器,则可能导致冲突将来添加具有相同名称的本机函数)。

StafanTony2020/03/09 12:54:38

这是流行答案的简化版本,它通过将字符串视为数组来获得第一个字母:

function capitalize(s)
{
    return s[0].toUpperCase() + s.slice(1);
}

更新:

根据下面的评论,这在IE 7或更低版​​本中不起作用。

更新2:

为了避免出现undefined空字符串(请参见下面的@ njzk2的注释),您可以检查一个空字符串:

function capitalize(s)
{
    return s && s[0].toUpperCase() + s.slice(1);
}
JinJinPro2020/03/09 12:54:38

在另一种情况下,我需要将其首字母大写,将其余字母小写。以下情况使我更改了此功能:

//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();
蛋蛋神乐2020/03/09 12:54:38

这是一种更加面向对象的方法:

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

您可以像下面这样调用该函数:

"hello world".capitalize();

预期输出为:

"Hello world" 
樱Davaid2020/03/09 12:54:38

如果您对发布的几种不同方法的性能感兴趣:

这是基于此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);
}

在此处输入图片说明

JinJin达蒙2020/03/09 12:54:38

在CSS中:

p:first-letter {
    text-transform:capitalize;
}