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

例如:

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


当前回答

这个代码在某些情况下可能工作得很好:

函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(capitalizeFirstLetter('foo')); // Foo // 但如果我们有这样的它不会工作好 console.log(capitalizeFirstLetter('fOo')); // FOo

但是,如果你真的想确保,只有第一个字母被资本化,其余的字母是由下层字母构成的,你可以调整代码如下:

函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } console.log(capitalizeFirstLetter('fOo')); // Foo

其他回答

我们将使用CSS来实现这一点,它也可以从外部CSS设置。

<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>

使用Vanilla JavaScript,我们可以:

let string = "test case"

string = string[0].toUpperCase() + string.substring(1)
//return "Test case"

此分類上一篇:</b/>

字符串[0].toUpperCase():将字符串中的第一个字符转换为顶部字符串

string.substring(1):在行中删除第一个字母并返回剩余的字符

text-transform="capitalize":在这个标签的顶部字母中创建每个字母的第一个字母. 如果您使用“uppercase”作为文本转换的值,标签中的每个字母将是一个字母。

任何类型的字符串都可以转换 -

此分類上一篇: Yourstring

var str = yOuRsTrING.toLowerCase(); // Output: yourstring
str.charAt(0).toUpperCase() + str.slice(1); // Output: Y + ourstring = Yourstring

此分類上一篇: I like this one:

yourString.replace(/(^[a-z])/i, (str, firstLetter) => firstLetter.toUpperCase())

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

功能包括:

/** 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

该方法将采取一个值,然后将其分成一系列的线条。

const firstLetterToUpperCase = value => {
 return value.replace(
    value.split("")["0"], // Split stirng and get the first letter 
    value
        .split("")
        ["0"].toString()
        .toUpperCase() // Split string and get the first letter to replace it with an uppercase value
  );
};