如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
// Uppercase first letter
function ucfirst(field) {
field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}
使用:
<input type="text" onKeyup="ucfirst(this)" />
其他回答
最简单的解决方案是:
let yourSentence = 'it needs first letter upper case';
yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);
或:
yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);
或:
yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);
好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。
因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。
首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉
你应该这样做:
let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
yourString.replace(/\w/, c => c.toUpperCase())
我发现这支箭的功能是最容易的。 替换符合你的字符的第一个字符(\w)字符,并将其转换为顶端。
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));