如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

关于TypeScript

  capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

其他回答

这将容忍可能领先的白空间,并不会错过一条线中的第一字母的目标,因此,它可能会改善已经在线上可用的好解决方案。

str = "   the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> "   The Eifel Tower";

但是,如果对白条行进行执行,则会导致“软”错误,为了避免这种可能的错误或对白条行或数字进行不必要的处理,可以使用温和的条件警卫:

+str!=+str ?  str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;

好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。

因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。

首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉

你可以做 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)

const capitalizeName = function (name) { 
    const names = name.split(' '); 
    const namesUpper = [];
    for (const n of names) {  
        namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
    } 
    console.log(namesUpper.join(' '));
 }; 
capitalizeName('the Eiffel Tower')

資本化和無資本化第一條線。

功能包括:

/** First Character uppercase */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/** First Character lowercase */
function uncapitalize(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

例1“第一个字符上方”:

alert(capitalize("hello world"));

标签:Hello World

示例2“第一字符下载案例”:

alert(uncapitalize("Hello World, today is sunny"));

此分類上一篇: Hello World, Today Is Sunny