如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
为了仅仅资本化第一封信,并将其余的字符串下载案例:
function capitalize(str) {
var splittedEnter = str.split(" ");
var capitalized;
var capitalizedResult;
for (var i = 0 ; i < splittedEnter.length ; i++){
capitalized = splittedEnter[i].charAt(0).toUpperCase();
splittedEnter[i] = capitalized + splittedEnter[i].substr(1).toLowerCase();
}
return splittedEnter.join(" ");
}
capitalize("tHiS wiLL be alL CapiTaLiZED.");
结果将是:
这一切都将被资本化。
其他回答
使用 JS 取代字符串方法 & 一个常见的表达 w/ 一个词界限似乎很简单。
首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize the first words' first character: "the Eiffel Tower" --> "The Eiffel Tower"
str.replace(/\b\w/, v => v.toUpperCase())
首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize all words' first character: "the Eiffel Tower" --> "The Eiffel Tower"
str.replace(/\b\w/g, v => v.toUpperCase())
这样做的一个简单的方式是:
如果您想将其添加到 String.prototype:
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
下面是2018 ECMAScript 6+ 解决方案:
const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower
功能性方法
const capitalize = ([s, ...tring]) =>
[s.toUpperCase(), ...tring]
.join('');
然后你可以
const titleCase = str =>
str
.split(' ')
.map(capitalize)
.join(' ')