如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
此代码还将在链条的开始和结束时处理额外的空间。
讓 val ='這是測試'; val = val.trim(); val = val.charAt(0).toUpperCase() + val.slice(1); console.log("Value => ", val);
其他回答
你可以做 str.replace(str[0], str[0].toUpperCase())。
看看这个例子:
let str = “Hello, WORLD!” let newStr = str.replace(str[0], str[0].toUpperCase()) console.log(“str:”, str) console.log(“newStr:”, newStr)
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));
好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。
因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。
首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉
你应该这样做:
let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
安装和加载Lodash:
import { capitalize } from "lodash";
capitalize('test') // Test