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

例如:

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


当前回答

首頁 〉外文書 〉文學 〉文學 〉Capitalize First Word: Shortest

text.replace(/(^.)/, m => m.toUpperCase())

每一个字:最短

text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

如果你想确保剩下的在底部:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

其他回答

yourString.replace(/\w/, c => c.toUpperCase())

我发现这支箭的功能是最容易的。 替换符合你的字符的第一个字符(\w)字符,并将其转换为顶端。

如果您想修改全覆文本,您可能希望修改其他例子如下:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

这将确保下列文本进行更改:

TEST => Test
This Is A TeST => This is a test
// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

使用:

<input type="text" onKeyup="ucfirst(this)" />

如同它:

function capitalize(string,a) {
    var tempstr = string.toLowerCase();
    if (a == false || a == undefined)
        return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
    else {
        return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
    }
}


capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!

capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!

https://jsfiddle.net/dgmLgv7b/

你可以做这样的事情:

mode =  "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);

这将打印

线条