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

例如:

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


当前回答

如果您使用 Underscore.js 或 Lodash, underscore.string 图书馆提供链接扩展,包括资本化:

_.capitalize(string) 将序列的第一字母转换为顶端。

例子:

_.capitalize("foo bar") == "Foo bar"

其他回答

函数 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'));

下面是2018 ECMAScript 6+ 解决方案:

const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower

let capitalize = (strPara)=>{
    let arr = Array.from(strPara);
    arr[0] = arr[0].toUpperCase();
    return arr.join("");
}

let str = capitalize("this is a test");
console.log(str);

一条线路:

此分類上一篇: 重定向,重定向,重定向,重定向,重定向

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

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

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

假设你的字符串在一个变量 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 按钮查看结果