如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/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 );
}
}
}
其他回答
下面是更清洁、更美丽的版本。
var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());
结果:
這是一個測試 -> 這是一個測試
这就是同样的行动:
var newStr = string.slice(0,1).toUpperCase() + string.slice(1);
适用于所有 Unicode 字符的解决方案
57 81 不同答案这个问题,一些离主题,但其中没有一个提出重要问题,没有一个列出的解决方案将与亚洲字符, emoji,和其他高 Unicode 点值字符在许多浏览器工作。
const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toUpperCase() + S.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toUpperCase() + S.substring(2) :
S.charAt(0).toUpperCase() + S.substring(1)
);
};
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toLocaleUpperCase() + S.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toLocaleUpperCase() + S.substring(2) :
S.charAt(0).toLocaleUpperCase() + S.substring(1)
);
};
请注意,上述解决方案试图计算 UTF-32. 然而,规格正式表示,浏览器必须在 UTF-16 地图中完成一切。 然而,如果我们都聚集在一起,做我们的部分,并开始为 UTF32 做好准备,那么 TC39 可能会允许浏览器开始使用 UTF-32 (就像 Python 如何使用 24 位字符的每个字符一样)
在CSS中:
p::first-letter {
text-transform:capitalize;
}
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));