如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
一个小改进 - 每个字在标题。
String.prototype.toTitleCase = function(){
return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}
var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!
其他回答
下面是更清洁、更美丽的版本。
var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());
结果:
這是一個測試 -> 這是一個測試
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
已经有这么多好答案,但你也可以使用一个简单的CSS转换:
text-transform: capitalize;
div.text-capitalize { 文本转型:资本化; } <h2>文本转型:资本化:</h2> <div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
这样做的一个简单的方式是:
如果您想将其添加到 String.prototype:
简单的ES6合成与模板链
const capitalize = (str) => { return `${str[0].toUpperCase()}${str.slice(1)}` // return str[0].toUpperCase() + str.slice(1) // without template string } console.log(capitalize(“这是一个测试”)); console.log(capitalize(“埃菲尔塔”)); console.log(capitalize(“/index.html”)); /* “这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/inde”