【问题标题】:How to replace certain letters in an array with an underscore如何用下划线替换数组中的某些字母
【发布时间】:2021-01-19 06:15:57
【问题描述】:

我正在尝试使文本显示在输入框下方,其中一些字母应替换为下划线。此文本将是用户应输入以获得正确输出的答案。

我希望循环用_ 替换像 e 这样的字母,但它什么也没做。没有错误消息,它只是不替换字母 e。我试图放置一个for 循环,我在其他地方发现了如何替换数组元素中的某些字符,但没有任何效果。

这里是JS代码:

let array = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime']
let arraySecond = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime']; 

//The other array is the one that shows the element, 
//that matches the first array, but with "_", instead of certain letters

document.getElementById('check').addEventListener('click', thisFunction);

function thisFunction() {
   let value = document.getElementById('input').value;
   
   if (value == theColor) {
    alert(`Congrats you gussed right, its ${value}`)
        } else {
    alert(`Oof, your guess was incorrect, it\'s ${array[randomizedArray]}`)
    }
}

let randomizedArray = Math.floor(Math.random() * array.length);

let theColor = array[randomizedArray]; 

//One thing the code above is used for is be in the for loop, to replace letters

for (let i = 0; i < theColor.length; i++) {
    theColor[i] = theColor[i].replace('e', '_');
} 

//This loop that should do the replacing, but it doesn't work

document.getElementById('output').innerHTML = theColor;

【问题讨论】:

  • 你能解释一下你想要做什么,例如您想用_ 替换字母e(例如)的所有 个实例,还是能够决定替换哪些实例?
  • 所以程序会选择数组中的某个元素。让我们说蓝色,因为它是数组中的一个元素。然后它将用下划线替换 e,下划线应显示为 blu_。这部分是用第二个数组完成的,第一个是供用户输入的。
  • 好的,我明白了,但是如果这个词是“绿色”呢?它应该替换它找到的所有es 还是只替换一个?
  • 是的 gr__n 像这样

标签: javascript arrays for-loop replace


【解决方案1】:

您正在对单词的单个字母而不是整个单词使用replace 函数 - 您无需遍历每个字母来替换它们。

根据您想要replace 的具体内容,您可以按如下方式进行操作(以e 为例):

  • 替换字母的第一个实例theColor.replace('e', '_');
  • 替换所有实例theColor.replace(/e/g, '_'); - 注意/.../g 表示进行全局搜索和替换。
  • 不区分大小写的替换:将/gi添加到上面的theColor.replace(/e/gi, '_');

但是我的猜测是,您需要替换的不仅仅是一个特定的字母,因此您可以一次性替换多个字母(例如 a、e、i、o 和 u),如下所示:

  • 替换多个字母的所有实例theColor.replace(/aeiou/gi, '_'); - 将//gi 之间的所有 字母替换为_

示例:

var theColor = "green";
console.log("Replace first instance of e in "+theColor+": " 
            + theColor.replace('e', '_'));

var theColor = "GREeN";
console.log("Replacing all instances of e (case insensitive) in "+theColor+": " 
            + theColor.replace(/e/gi, '_'));

var theColor = "orange";
console.log("Replacing all vowels in one go in "+theColor+": "
            + theColor.replace(/[aeiou]/gi, '_'));

在您的代码中替换所有元音(a、e、i、o 或 u),例如,您只需执行以下操作:

document.getElementById('output').innerHTML = theColor.replace(/[aeiou]/gi, '_');

注意,不要直接更改theColor 的值,因为这是您用来比较猜测的值。上面的行只替换了显示的颜色,而不是颜色本身的名称。

工作示例

let array = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime']
let arraySecond = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime'];

//The other array is the one that shows the element, 
//that matches the first array, but with "_", instead of certain letters
document.getElementById('check').addEventListener('click', thisFunction);

function thisFunction() {
  let value = document.getElementById('input').value;

  if (value == theColor) {
    alert(`Congrats you gussed right, its ${value}`)
  } else {
    alert(`Oof, your guess was incorrect, it\'s ${array[randomizedArray]}`)
  }
}

let randomizedArray = Math.floor(Math.random() * array.length);
let theColor = array[randomizedArray];

/* THIS IS WHERE THE NEW CODE IS
   DISPLACE THE COLOR WITH ALL a,e,i,o OR u REPLACED WITH _ */
document.getElementById('output').innerHTML = theColor.replace(/[aeiou]/gi, '_');
<input id="input">
<button id="check">Check</button>
<div id="output"></div>

参考MDN Docs for replace function

【讨论】:

  • 感谢您的帮助和解释!
  • @DanAmazing 很高兴为您提供帮助!我看到了一条关于传递给替换函数的评论的通知,但它似乎已被删除。我假设您找到了答案,但如果没有,replace 函数可以采用正则表达式模式,例如/abc/g - 您可以在链接到答案 (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) 的文档中找到有关 replace 函数的更多信息,该页面还包含指向正则表达式的链接,以获取有关正则表达式模式的更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2018-11-25
  • 2013-02-10
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多