如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

简单的ES6合成与模板链

const capitalize = (str) => { return `${str[0].toUpperCase()}${str.slice(1)}` // return str[0].toUpperCase() + str.slice(1) // without template string } console.log(capitalize(“这是一个测试”)); console.log(capitalize(“埃菲尔塔”)); console.log(capitalize(“/index.html”)); /* “这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/inde”

其他回答

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'
String.prototype.capitalize = function(){
    return this.replace(/(^|\s)([a-z])/g, 
                        function(m, p1, p2) {
                            return p1 + p2.toUpperCase();
                        });
};

使用:

capitalizedString = someString.capitalize();

此分類上一篇: This Is a Text String

使用此 Node.js 模块, http://stringjs.com/ 包,以资本化您的行:

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'

只是因为你可以,这并不意味着你应该,但是. 它需要 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("");
};

在CSS中:

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