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

例如:

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


当前回答

第一封信与验证的资本化

function capitalizeFirstLetter(str) {
    return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}

测试

console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""

其他回答

一条线路:

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

安装和加载Lodash:

import { capitalize } from "lodash";

capitalize('test') // Test

总是更好地处理这些类型的东西使用CSS首先,一般来说,如果你可以用CSS解决一些事情,先去,然后尝试JavaScript解决你的问题,所以在这种情况下尝试使用CSS的第一字母,并应用文本转换:资本化;

所以,试着为此创建一个类,这样你就可以在全球范围内使用它,例如:.first-letter-uppercase 并在你的 CSS 中添加下面的类似内容:

.first-letter-uppercase:first-letter {
    text-transform:capitalize;
}

另一个选项是JavaScript,所以最好的会是这样的东西:

function capitalizeTxt(txt) {
  return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}

把它称为:

capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html');  // return '/index.html'
capitalizeTxt('alireza');  // return 'Alireza'
capitalizeTxt('dezfoolian');  // return 'Dezfoolian'

如果你想重复使用它一次又一次,最好将其添加到JavaScript Native String,所以如下:

String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

把它称为下面的:

'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt();  // return '/index.html'
'alireza'.capitalizeTxt();  // return 'Alireza'

这就是同样的行动:

var newStr = string.slice(0,1).toUpperCase() + string.slice(1);

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

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

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

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

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