从数组中的每个字符串值中删除一个常用字

时间:2013-05-12 15:08:28

标签: javascript jquery

我正在动态填充数组,该数组基于页面id标记上的所有video

如何从每个数组项的值中删除单词dog?到目前为止,这是填充的数组,我只需要为每个数组项删除单词dog

var players = new Array();
$("video").each(function(){ 
    players.push($(this).attr('id'));
});

所以它会来自:

["video_12_dog", "video_13_dog"]

为:

["video_12", "video_13"]

1 个答案:

答案 0 :(得分:3)

您可以迭代数组并在每个元素上调用replace()(作为字符串):

function removeWord(arr, word) {
    for (var i = 0; i < arr.length; i++){
        arr[i] = arr[i].replace(word,'');
    }
}
var aaa = ['value_1_dog', 'value_dog_2', 'dog_value3'];
removeWord(aaa, 'dog');
console.log(aaa); // ["value_1_", "value__2", "_value3"]

var question = ["video_12_dog","video_13_dog"]
removeWord(question, '_dog');
console.log(question); // ["video_12","video_13"]

小提琴:http://jsfiddle.net/9KPkh/