如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
我只会用一个常见的表达式:
myString = ' the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());
其他回答
如果您对每个字母的第一字母进行资本化,并且您的 usecase 在 HTML 中,您可以使用以下 CSS:
<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>
此分類上一篇: CSS Text-Transform Property(W3Schools)
你可以这样做,这样一行。
string[0].toUpperCase() + string.substring(1)
function cap(input) {
return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
// For other sentences in the text
return match.toUpperCase();
}).replace(/^\W*\w/, function(match, capture) {
// For the first sentence in the text
return match.toUpperCase();
});;
}
var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
// Output: Hi, dear user. It is a simple test. See you later!
// Bye
创建一行资本的第一字母
第一個解決方案
“这是一个测试” → “这是一个测试”
var word = "this is a test"
word[0].toUpperCase();
他说:“这是一个测试。
第二個解決方案 第一個字的條件資本
“这是一个测试” → “这是一个测试”
function capitalize(str) {
const word = [];
for(let char of str.split(' ')){
word.push(char[0].toUpperCase() + char.slice(1))
}
return word.join(' ');
}
capitalize("this is a test");
他说:“这是一个测试。
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"