如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

使用 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())

其他回答

功能性方法

const capitalize = ([s, ...tring]) =>
  [s.toUpperCase(), ...tring]
    .join('');

然后你可以

const titleCase = str => 
  str
    .split(' ')
    .map(capitalize)
    .join(' ')

你可以做这样的事情:

mode =  "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);

这将打印

线条

你应该这样做:

let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);

有一个非常简单的方式来实现它通过替代。

'foo'.replace(/^./, str => str.toUpperCase())

结果:

'Foo'

您可以使用 regex 方法:

str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());