【问题标题】:JavaScript-Creating a Function to capitalise the first letter of a string [duplicate]JavaScript-创建一个函数以大写字符串的第一个字母[重复]
【发布时间】:2021-03-29 19:38:46
【问题描述】:

我在创建一个将字符串首字母大写的函数时遇到了麻烦。当我输入小写的单词时,我可以将字符串大写,但不能大写。非常感谢您对这个问题的帮助,请参阅下面的脚本:

function captialise(str) {
    str = prompt("Enter a string");
    console.log(str[0].toUpperCase() + str.substring(1))
}

captialise();

【问题讨论】:

  • 您应该强制字符串的其余部分为小写:+ str.substring(1).toLowerCase()。就像你对第一个字母所做的那样。
  • 为什么期望一个字符串作为参数,同时提示一个字符串?这没有任何意义。
  • 为什么从我的答案中减去.. 当它 100% 正确时.. 这里的毒性是真实的
  • 这个论点也完全没用,但它没有伤害任何东西..我认为这只是花花公子的风格

标签: javascript html


【解决方案1】:

逻辑上的问题是,您将第一部分大写是的,但您没有降低其他部分

function captialise(str) {
    str = prompt("Enter a string");
    console.log(str[0].toUpperCase() + str.substring(1).toLowerCase())
}

captialise();

【讨论】:

    【解决方案2】:

    第一个字符大写,其余部分小写。 sn-p 使用更现代的脚本(该函数使用template literal

    const capitalize = str => str.slice 
      ? `${str.slice(0,1).toUpperCase()}${str.slice(1).toLowerCase()}` 
      : str;
    
    const str1 = `someSTRING`; 
    const str2 = `someotherstring`; 
    const str3 = `s23omeotherstring`; 
    const str4 = prompt('enter something'); 
    
    console.log(capitalize(str1));
    console.log(capitalize(str2));
    console.log(capitalize(str3));
    console.log(capitalize(str4));

    【讨论】:

    • 如果我输入的不是字符串,则会出错。例如一个数字
    • 数字大写没有意义吗?
    • @mplungjan 很公平,已编辑答案。 prompt 中的数字将作为字符串返回。
    • @KooiInc 是的,但您之前的代码中没有提示
    【解决方案3】:

    建议有一个函数返回你的名字。

    你也需要将字符串的其余部分小写,我会首先测试你是否有一个字符串

    我选择使用 + 而不是模板文字,因为在这种简单的情况下更容易阅读

    const captialise = str => str && typeof str === "string" ? 
      str.slice(0,1).toUpperCase() + str.slice(1).toLowerCase() : 
      str;
    
    
    console.log(
       captialise(prompt("Enter a string"))
    )

    【讨论】:

      【解决方案4】:

      有很多方法可以做到,我相信以前在这里问过很多次, 这是一行:

      function captialise(str) {
          str = prompt("Enter a string");
          console.log(`${str[0].toUpperCase()}${str.substring(1).toLowerCase()}`);
        
      }
      
      captialise();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-24
        • 2017-03-20
        • 1970-01-01
        相关资源
        最近更新 更多