如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
将所有单词的第一字母分为一个字符串:
function capitalize(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.toLowerCase().slice(1)).join(' ');
}
其他回答
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));
这个解决方案可能是新的,也许是最简单的。
函数第一UpperCase(输入) {返回输入[0].toUpperCase() + input.substr(1); } console.log(第一UpperCase(“资本化第一字母”));
带有箭功能
let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"
用火箭功能,另一种解决方案
let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"
与 Array 和 地图()
let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]
好吧,所以我是新的JavaScript. 我无法得到上面的为我工作. 所以我开始把它自己。
String name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
在这里,我从一个表格中获取变量(它也手动工作):
String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
出发:“我是聪明的......”;
使用 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())