如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
这里是我的尝试,使一个普遍的功能,只有第一字母,或每个字母的第一字母,包括单词分开的单词(如一些第一名在法语)。
默认情况下,该函数仅将第一个字母归功,其余的字母无触。
参数:
lc: 忠于强迫下载的所有字(s): 忠于资本化每一个字
if( typeof String.prototype.capitalize !== "function" ) {
String.prototype.capitalize = function( lc, all ) {
if( all ) {
return this.split( " " )
.map( currentValue => currentValue.capitalize( lc ), this )
.join( " " )
.split( "-" )
.map( currentValue => currentValue.capitalize( false ), this )
.join( "-" );
} else {
return lc
? this.charAt( 0 ).toUpperCase() + this.slice( 1 ).toLowerCase()
: this.charAt( 0 ).toUpperCase() + this.slice( 1 );
}
}
}
其他回答
ucfirst函数工作,如果你这样做。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
谢谢JP的解释。
string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());
安装和加载Lodash:
import { capitalize } from "lodash";
capitalize('test') // Test
下面是更清洁、更美丽的版本。
var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());
结果:
這是一個測試 -> 這是一個測試
使用 Tailwind CSS
<p class="capitalize">The quick brown fox</p>
此分類上一篇: Quick Brown Fox
(src: https://tailwindcss.com/docs/text-transform#transforming-text)