如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
使用 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())
其他回答
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'
任何类型的字符串都可以转换 -
此分類上一篇: Yourstring
var str = yOuRsTrING.toLowerCase(); // Output: yourstring
str.charAt(0).toUpperCase() + str.slice(1); // Output: Y + ourstring = Yourstring
这个代码在某些情况下可能工作得很好:
函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(capitalizeFirstLetter('foo')); // Foo // 但如果我们有这样的它不会工作好 console.log(capitalizeFirstLetter('fOo')); // FOo
但是,如果你真的想确保,只有第一个字母被资本化,其余的字母是由下层字母构成的,你可以调整代码如下:
函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } console.log(capitalizeFirstLetter('fOo')); // Foo
使用 Tailwind CSS
<p class="capitalize">The quick brown fox</p>
此分類上一篇: Quick Brown Fox
(src: https://tailwindcss.com/docs/text-transform#transforming-text)
您可以使用 regex 方法:
str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());