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

例如:

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


当前回答

咖啡文字

ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

作为一个严格的原型方法:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)

其他回答

下面是更以对象为导向的方法:

Object.defineProperty(String.prototype, 'capitalize', {
  value: function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  },
  enumerable: false
});

你会称之为这个功能,如下:

"hello, world!".capitalize();

预计产量是:

"Hello, world!"

我更喜欢使用一个以功能方式为导向的解决方案(例如地图序列):

Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');
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

如果你去其中一个 regex 答案,请记住,它们只会与 ASCII 字符一起工作. 所有的 Unicode 字母都不会被打破. XRegExp 图书馆和其 Unicode 插件解决这个问题,如果你想与 regex 保持。

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