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

例如:

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


当前回答

功能性方法

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

然后你可以

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

其他回答

这是一个简单的

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

如果您的项目中有Lodash,请使用UpperFirst

咖啡文字

ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

作为一个严格的原型方法:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)

这将容忍可能领先的白空间,并不会错过一条线中的第一字母的目标,因此,它可能会改善已经在线上可用的好解决方案。

str = "   the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> "   The Eifel Tower";

但是,如果对白条行进行执行,则会导致“软”错误,为了避免这种可能的错误或对白条行或数字进行不必要的处理,可以使用温和的条件警卫:

+str!=+str ?  str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);