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

例如:

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


当前回答

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

其他回答

在 CoffeeScript 中,添加一个字符串的原型:

String::capitalize = ->
  @substr(0, 1).toUpperCase() + @substr(1)

使用将是:

"woobie".capitalize()

谁得益:

"Woobie"

我們可以獲得第一個角色與我最喜歡的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();
  });
};

只有CSS

如果转换仅需要在网页上显示:

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

尽管被称为“::第一字”,但它适用于第一个字符,即在 %a 字符的情况下,这个选择器将适用于 % 并且作为这样一个不会被资本化。

ES2015 单线

const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);

注意事项

在我所执行的指标中,在 string.charAt(0) 和 string(0) 之间没有显著的差异。 但是,请注意,该 string(0) 会为一个空的 string 不定义,因此该函数必须重写以使用“string && string(0)”,这与替代品相比是过于垂直的。

与 substring() 和 slice() 之间的比较

差异在今天相当微小(自己进行测试):

21,580,613.15 ops/s ±1.6% for substring(), 21,096,394.34 ops/s ±1.8% (2.24% 缓慢) for slice()。

此分類上一篇

如果你需要所有的字母,从一个字母开始,你可以使用以下函数:

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"

这个代码在某些情况下可能工作得很好:

函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(capitalizeFirstLetter('foo')); // Foo // 但如果我们有这样的它不会工作好 console.log(capitalizeFirstLetter('fOo')); // FOo

但是,如果你真的想确保,只有第一个字母被资本化,其余的字母是由下层字母构成的,你可以调整代码如下:

函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } console.log(capitalizeFirstLetter('fOo')); // Foo