【问题标题】:Replace Vowels in a String with their index in the String Using JavaScript使用 JavaScript 将字符串中的元音替换为字符串中的索引
【发布时间】:2018-11-29 03:04:43
【问题描述】:

我需要用字符串中的索引 + 1 替换字符串中的每个元音。 (函数名 = vowel2index)
输出示例:

 vowel2index('this is my string') == 'th3s 6s my str15ng'

我希望这个例子能说明我想要做什么。我尝试使用如下替换方法:

  str.replace(/[aeiou]/gi, str.indexOf(/[aeiou]/gi);

但这并没有解决问题。我也试过下面的代码,但我不知道从 IF 语句到哪里去(我还没有使用数组元音):

 function vowel2index(str) {
 let vowels = ["a", "e", "i", "o", "u"];
 let arr = [];
 for(i = 0; i < str.length; i++){
     if (str[i] === /[aeiou]/gi) {
        arr.push(str.replace(str[i], indexOf(str[i])+1));
     }

任何帮助表示赞赏。作为一个仅供参考,这个问题来自代码战。

【问题讨论】:

    标签: javascript arrays regex loops


    【解决方案1】:

    你快到了。 .replace 函数 accepts an offset parameter 包含当前匹配的索引,因此您可以只使用替换函数,并返回该偏移量加一。不需要元音数组,只需使用模式中的元音字符集即可:

    function vowel2index(str) {
      return str.replace(/[aeiou]/gi, (vowel, offset) => offset + 1);
    }
    console.log(vowel2index('this is my string')); // == 'th3s 6s my str15ng');

    【讨论】:

    • (重复评论):谢谢!我仍然不清楚偏移量是什么。我从 MDN 网络文档中阅读了偏移量的定义:“匹配的子字符串在被检查的整个字符串中的偏移量。(例如,如果整个字符串是 'abcd',匹配的子字符串是 'bc',那么这个参数将是 1.)" 你介意澄清一下吗?再次感谢。
    • "bc" 子字符串的开头在输入字符串的索引 1 处,因此在这种情况下 offset 是 1。 (字符串开头的匹配项的索引为 0)
    • 当某个答案解决了您的问题时,请考虑将其标记为已接受以表明您的问题已解决:)
    • 你是怎么做到的?
    【解决方案2】:

    远没有上面的@CertainPerformance 答案那么干净,但蛮力解决方案是:

    function vowel2index(string) {
    
      var result = [];
    
      for(var i = 0; i < string.length; i++) {
        var c = string.charAt(i);
        if(c.match(/[aeiou]/gi)) {
          result.push(i + 1);
        } else {
          result.push(c);
        }
      }
      return result.join('');
    }
    

    【讨论】:

      【解决方案3】:

      你可以试试这个伙伴。

      const vowel2index = str => str.replace(/[aeiou]/gi, (_, offset) => offset+1) 
      
      
      console.log(vowel2index('this is my string'))

      附: :它将清除所有测试用例,因为我已经解决了那个 kata。 (很高兴见到来自 Codewars 的人♡)?

      【讨论】:

      • 谢谢!我仍然不清楚偏移量是什么。我从 MDN 网络文档中阅读了偏移量的定义:“匹配的子字符串在被检查的整个字符串中的偏移量。(例如,如果整个字符串是 'abcd',匹配的子字符串是 'bc',那么这个参数将是 1.)" 你介意澄清一下吗?再次感谢。
      • 是的!所以偏移量将返回子字符串匹配的开始索引,所以这里我们只匹配一个字符,所以只会得到那个字符的索引(它是基于 0 的,所以我们根据需要添加 1)。跨度>
      • 谢谢!再次感谢。
      【解决方案4】:

      试试这个:

      function vowel2index(str) {
       for(i = 0; i < str.length; i++){
           if (str[i] === /[aeiou]/gi) {
              str.replace(str[i], indexOf(str[i])+1);
           }
      

      【讨论】:

      • 我试过这个方法,但是没用。无论如何,谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 2012-06-02
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      相关资源
      最近更新 更多