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

例如:

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


当前回答

优雅

const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;

其他回答

我在我的开发环境中使用这些线路,特别是当我与HTTP等API合作时:

假设您有一个 HTTP 标题,您希望在其名义中资本化每个初始字母,并在其组成词之间添加混合物。

'access control allow origin'
    .replace(/\b\w/g, function (match) {
        return match.toUpperCase();
    })
    .split(' ')
    .join('-');

// Output: 'Access-Control-Allow-Origin'

这可能不是最优雅和最有吸引力的功能定义,但它肯定会完成工作。

下面是更清洁、更美丽的版本。

var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());

结果:

這是一個測試 -> 這是一個測試

首先,我只是想清楚资本化在这个背景下意味着什么,“这条线是资本化”可靠的来源

你可以从例子中看到,只要这不是OP正在寻找的东西,它应该说的是“我如何制作一条线的第一字”(不资本化线)

function ucfirst (str) {
    return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}

解释

typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string

这将与任何论点或没有论点工作。

undefined         === ""
""                === ""
"my string"       === "My string"
null              === "Null"
undefined         === "";
false             === "False"
0                 === "0"
true              === "True"
[]                === ""
[true,0,"",false] === "True,0,,false"

如果您想修改全覆文本,您可能希望修改其他例子如下:

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

这将确保下列文本进行更改:

TEST => Test
This Is A TeST => This is a test

如果你去其中一个 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() 方法。