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

例如:

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


当前回答

带有箭功能

let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"

用火箭功能,另一种解决方案

let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"

与 Array 和 地图()

let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]

其他回答

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

此分類上一篇: Yourstring

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

在CSS中:

p::first-letter {
    text-transform:capitalize;
}

使用此 Node.js 模块, http://stringjs.com/ 包,以资本化您的行:

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'
function cap(input) {
    return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
         // For other sentences in the text
         return match.toUpperCase();
    }).replace(/^\W*\w/, function(match, capture) {
        // For the first sentence in the text
        return match.toUpperCase();
    });;
}

var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
// Output: Hi, dear user. It is a simple test. See you later!
// Bye

一个可能的解决方案:

function ConvertFirstCharacterToUpperCase(text) {
    return text.substr(0, 1).toUpperCase() + text.substr(1);    
}

使用此:

 alert(ConvertFirstCharacterToUpperCase("this is string"));

此分類上一篇: JS Fiddle