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

例如:

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


当前回答

一个简单的,紧凑的功能,将完成你的工作:

const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');

“Foo” > “Foo” “Foo Bar” > “Foo Bar”

其他回答

或者你可以使用Sugar.js资本()

例子:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'

有几种方法可以做到这一点,请尝试下面的

var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);

如果你很舒服的常规表达,你会这样做:

var upper = lower.replace(/^\w/, function (chr) {
  return chr.toUpperCase();
});

你甚至可以通过使用更现代化的合成来迈出一步:

const upper = lower.replace(/^\w/, c => c.toUpperCase());

此外,这也将照顾如示例中提到的负面场景,如从特殊字符开始的单词,如!@#$%^&*()}{{[];':",<>/?。

一条线(“输入线可以设置到任何条线”):

inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())

如果您想修改全覆文本,您可能希望修改其他例子如下:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

这将确保下列文本进行更改:

TEST => Test
This Is A TeST => This is a test

我只会用一个常见的表达式:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());