如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
函数 capitalizeEachWord(str) { return str.replace(/\w\S*/g,函数(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } document.write(capitalizeEachWord('foo BAR God bAD'));
其他回答
一个简单的,紧凑的功能,将完成你的工作:
const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');
“Foo” > “Foo” “Foo Bar” > “Foo Bar”
此代码还将在链条的开始和结束时处理额外的空间。
讓 val ='這是測試'; val = val.trim(); val = val.charAt(0).toUpperCase() + val.slice(1); console.log("Value => ", val);
使用 Tailwind CSS
<p class="capitalize">The quick brown fox</p>
此分類上一篇: Quick Brown Fox
(src: https://tailwindcss.com/docs/text-transform#transforming-text)
下面是2018 ECMAScript 6+ 解决方案:
const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower
安装和加载Lodash:
import { capitalize } from "lodash";
capitalize('test') // Test