"This is a test""t..."> "This is a test""t..."/> "This is a test""t..."> "This is a test""t...">

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

JavaScript

Eva猿猿

2020-03-09

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

例如:

  • "this is a test" -> "This is a test"
  • "the Eiffel Tower" -> "The Eiffel Tower"
  • "/index.html" -> "/index.html"

第154篇《如何在JavaScript中将字符串的首字母大写?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

21个回答
猪猪GO 2020.03.09

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)
猪猪GO 2020.03.09
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

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
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
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
神无宝儿达蒙 2020.03.09
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

猴子Near 2020.03.09

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老丝Pro 2020.03.09

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
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
LEY蛋蛋Near 2020.03.09

在CSS中似乎更容易:

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

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

凯樱 2020.03.09

采用:

var str = "ruby java";

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

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

十三LEY 2020.03.09
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

我们可以得到第一个我最喜欢的角色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();
  });
};
LJinJin 2020.03.09

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

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

例:

_.capitalize("foo bar") == "Foo bar"
前端Stafan 2020.03.09

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

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(" ");
}
YOC71588217 2020.03.09
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

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

StafanTony 2020.03.09

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

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);
}
JinJinPro 2020.03.09

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

//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

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

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

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

"hello world".capitalize();

预期输出为:

"Hello world" 
樱Davaid 2020.03.09

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

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

在CSS中:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android