【问题标题】:Why does toLowerCase() does not work with replace()?为什么 toLowerCase() 不能与 replace() 一起使用?
【发布时间】:2021-09-01 21:54:02
【问题描述】:

Given 下面是一个简单的函数,可以将句子中的第一个单词大写
例如:INPUT: 'JavaSCRipt is The BEST'
输出:'JavaScript 是最好的'

const firstupper = function(str){
    const arr = str.split(' ');
    const newArr = [];
    for(let item of arr){
        item = item.toLowerCase();
        newArr.push(item.replace(item[0], item[0].toUpperCase()));
    }
    const newstr = newArr.join(' ');
    console.log(newstr);
}

firstupper('javaSCript is THE besT');

P.S -- 这段代码运行良好

为什么我不能先小写,然后在单行中替换大写的第一个字母 喜欢:newArr.push(item.toLowerCase().replace(item[0], item[0].toUpperCase()));

当我使用它编写代码时,如果它是大写,则将第一个单词更改为小写,反之亦然

例如:INPUT -> 'JAvaScript 是最好的' 输出 -> 'javascript 是最好的'

【问题讨论】:

    标签: javascript


    【解决方案1】:

    因为这会改变逻辑。在这个版本中,所有.push()操作中读取item都是小写的:

    item = item.toLowerCase();
    newArr.push(item.replace(item[0], item[0].toUpperCase()));
    

    但是在这个版本中,只有item第一个使用是小写的:

    newArr.push(item.toLowerCase().replace(item[0], item[0].toUpperCase()));
    

    item[0] 的引用仍然使用原来的大小写。为了使其具有相同的逻辑,您还需要在那里重复大小写更改:

    newArr.push(item.toLowerCase().replace(item.toLowerCase()[0], item.toLowerCase()[0].toUpperCase()));
    

    这显然太混乱了,不必要地重复操作。所以首选原来的工作版本。

    【讨论】:

    • 第一次使用小写是什么意思。另外,我们可以在 (item.toLowerCase()).replace..replace 周围使用括号......这行得通吗
    • @AbhishekPragada: 带有 push 操作的代码行读取了 item 变量 3 次。在工作示例中,该变量首先被其值的小写副本替换,因此该值的所有三种用途都参见小写版本。在非工作版本中,它永远不会被替换。小写操作在线发生并且只发生一次,所以只有那个使用是小写的。 item 变量的其余两个用途是读取其原始的非小写值。不,使用括号不会改变这一点。
    【解决方案2】:

    这会有所帮助

    const str = 'JavaSCRipt is The BEST';
    
    //split the above string into an array of strings 
    //whenever a blank space is encountered
    
    const arr = str.split(" ");
    
    //loop through each element of the array and capitalize the first letter.
    
    
    for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i].toLowerCase();
        arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
    
    }
    
    //Join all the elements of the array back into a string 
    //using a blankspace as a separator 
    const str2 = arr.join(" ");
    console.log(str2);
    
    //Outptut: Javascript Is The Best
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-09
      • 2021-06-14
      • 2012-10-09
      • 2020-03-18
      • 2017-11-21
      • 2019-04-11
      • 2012-09-19
      • 2013-12-30
      相关资源
      最近更新 更多