如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
使用 RamdaJs 的另一种方式,是功能编程方式:
firstCapital(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return fn(str);
}
用多个字在一个字符串:
firstCapitalAllWords(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return R.map(fn,R.split(' ', str)).join(' ');
}
其他回答
这就是我宗教上所使用的:
function capitalizeMe(str, force){
str = force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
var firstName = capitalizeMe($firstName.val());
当我们说资本时,这意味着每个字中的第一个字母应该在上方,而成功的字符则在下方。
第一個函數下有兩個函數,第一個函數將使一條字符的第一個字符在上方,成功的字符在下方,第二個函數將使一條字符在標題字符,這意味著每個字符的第一個字符將在頭部。
// Will make will first letter of a sentence or word uppercase function capital(word){ word = word.toLowerCase() return word[0].toUpperCase() + word.substring(1); } // Will make first letter in each word capital function titleCase(title) { title = title.toLowerCase(); const words = title.split(' '); const titleCaseWords = words.map(word) => word[0].toUpperCase() + word.substring(
ucfirst函数工作,如果你这样做。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
谢谢JP的解释。
或者你可以使用Sugar.js资本()
例子:
'hello'.capitalize() -> 'Hello'
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
下面有一个函数称为ucfirst((缩写为“上例第一字母”):
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
您可以通过称 ucfirst(“某些链条”)来资本化一个链条 - 例如,
ucfirst("this is a test") --> "This is a test"
在第一行中,它提取第一Letter,然后在第二行中,它通过呼叫第一Letter.toUpperCase()来资本化第一Letter,并将其与其余的行列相结合,这是通过呼叫str.substr(1)来找到的。
你可能认为这会失败一个空的线条,而且实际上在一个语言如C,你会不得不为此加密,但是在JavaScript中,当你采取一个空的线条,你只是得到一个空的线条。