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

例如:

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


当前回答

我在我的开发环境中使用这些线路,特别是当我与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 = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);

函数 capitalizeEachWord(str) { return str.replace(/\w\S*/g,函数(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } document.write(capitalizeEachWord('foo BAR God bAD'));

var capitalizeMe = "string not starting with capital"

资本化与substr

var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);

好吧,这里是一个更简单的方法,空间线和这一切。

首先,你應該知道,一條線是一系列字符。

这个答案应该在所有空间线上工作。

假设你的字符串在一个变量 yourString:

const yourString = "el salvacion sucks" const capitalizeString = yourString.split(" ").长度 > 0? yourString.split(" ").map((item) => 项目[0].toUpperCase() + 项目.substring(1)).join(" ") : yourString[0].toUpperCase() + yourString.substring(1) console.log(capitalizeString)

点击 Run Code Snippet 按钮查看结果