替换数组中的一个字符串

Replace one string within array

本文关键字:一个 字符串 数组 替换      更新时间:2023-09-26

我有以下数组:

etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest

我想从数组中删除输入框的值,这是我正在尝试的:

var el = document.getElementById('searchInput').value; // this is "test"
var toSearchFor = eld.slice(0,10); // the array above
for(var i=0; i < toSearchFor.length; i++) {
   toSearchFor[i] = toSearchFor[i].replace(/el/g, "");
}

它只是没有将"测试"替换为"

我该怎么做?

您可以使用Array.filter(请参阅 MDN)来过滤掉所需的值:

var arr = 'etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest'.split(',')
   ,val = 'test'
   
document.querySelector('#result')
  .innerHTML = arr.filter(function (v) {return v != val});
<div id="result"></div>

此 jsFiddle 中的文本字段示例

对于存储在变量中的字符串的全局替换,您需要显式创建 RegExp 的实例,如下所示:

var regex = new RegExp(el, "g");

然后在替换功能中使用它:

toSearchFor[i] = toSearchFor[i].replace(regex, "");

代码的问题在于正则表达式:/el/g 。这是试图匹配字母el,而不是它在el变量中的任何内容。您可以使用 RegExp 解释器来完成它。

// ...
regexp = new RegExp(el); // No need to use 'g' here since you're looking for the whole word
toSearchFor[i] = toSearchFor[i].replace(regexp, "");
// ...

这是另一种方法:

var eld = ['etst','tset','tets','ttest','teest','tesst','testt','4est','test','dest'];
// var el = document.getElementById('searchInput').value;
var el = 'test';
console.log(eld);
var index = eld.indexOf(el);
if (index >= 0) {
    eld[index] = '';    
}
console.log(eld);

下面是输出:

["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "test", "dest"]
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "", "dest"]

在本例中,我们使用 Array.prototype.indexOf,它返回可以在数组中找到给定元素的第一个索引,以便我们可以直接访问该元素(如果找到)。

我希望这有所帮助!