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

例如:

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


当前回答

資本化和無資本化第一條線。

功能包括:

/** First Character uppercase */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/** First Character lowercase */
function uncapitalize(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

例1“第一个字符上方”:

alert(capitalize("hello world"));

标签:Hello World

示例2“第一字符下载案例”:

alert(uncapitalize("Hello World, today is sunny"));

此分類上一篇: Hello World, Today Is Sunny

其他回答

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

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

结果:

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

下面是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

我知道这是一个古老的问题,有很多答案,但这里是我的快速剪辑。

const capitalize = (str) => str?.split('').map( (e, i) => i === 0 ? e.toUpperCase() : e ).join('')

创建一行资本的第一字母

第一個解決方案

“这是一个测试” → “这是一个测试”

var word = "this is a test"
word[0].toUpperCase();

他说:“这是一个测试。

第二個解決方案 第一個字的條件資本

“这是一个测试” → “这是一个测试”

function capitalize(str) {

    const word = [];

    for(let char of str.split(' ')){
        word.push(char[0].toUpperCase() + char.slice(1))
    }

    return word.join(' ');

}

 capitalize("this is a test");

他说:“这是一个测试。

/*
 * As terse as possible, assuming you're using ES version 6+
 */
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());

console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\