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

例如:

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


当前回答

首頁 〉外文書 〉文學 〉文學 〉Capitalize First Word: Shortest

text.replace(/(^.)/, m => m.toUpperCase())

每一个字:最短

text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

如果你想确保剩下的在底部:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

其他回答

尝试下列功能:

function capitalize (string) {
  return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}

使用:

capitalize('hello, world!')

结果:

Hello, world!
/*
 * As terse as possible, assuming you're using ES version 6+
 */
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());

console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\

下面是2018 ECMAScript 6+ 解决方案:

const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower

使用步枪功能:

const capitalize = string => string[0].toUpperCase() + string.slice(1)
s[0].toUpperCase``+s.substr`1`

let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )