如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"
其他回答
ucfirst函数工作,如果你这样做。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
谢谢JP的解释。
好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。
因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。
首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉
下面是更清洁、更美丽的版本。
var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());
结果:
這是一個測試 -> 這是一個測試
使用 JS 取代字符串方法 & 一个常见的表达 w/ 一个词界限似乎很简单。
首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize the first words' first character: "the Eiffel Tower" --> "The Eiffel Tower"
str.replace(/\b\w/, v => v.toUpperCase())
首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize all words' first character: "the Eiffel Tower" --> "The Eiffel Tower"
str.replace(/\b\w/g, v => v.toUpperCase())
总是更好地处理这些类型的东西使用CSS首先,一般来说,如果你可以用CSS解决一些事情,先去,然后尝试JavaScript解决你的问题,所以在这种情况下尝试使用CSS的第一字母,并应用文本转换:资本化;
所以,试着为此创建一个类,这样你就可以在全球范围内使用它,例如:.first-letter-uppercase 并在你的 CSS 中添加下面的类似内容:
.first-letter-uppercase:first-letter {
text-transform:capitalize;
}
另一个选项是JavaScript,所以最好的会是这样的东西:
function capitalizeTxt(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}
把它称为:
capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html'); // return '/index.html'
capitalizeTxt('alireza'); // return 'Alireza'
capitalizeTxt('dezfoolian'); // return 'Dezfoolian'
如果你想重复使用它一次又一次,最好将其添加到JavaScript Native String,所以如下:
String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
把它称为下面的:
'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt(); // return '/index.html'
'alireza'.capitalizeTxt(); // return 'Alireza'