我如何用javascript过滤一个语句的一些单词?

时间:2014-01-20 16:18:14

标签: javascript prototype

我想用javascript过滤一些语句的一些单词。 我必须过滤单词并且必须替换单词:

var words = [
{'badword':/dog/, 'goodword':'1'},
{'badword':/gav/ , 'goodword':'5'},
{'badword':/folan/ , 'goodword':':6'}
// .
//.
//.
//and more
];

例如,我想/狗/过滤器和1更换。 我怎么样?

1 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/billymoon/RF7Gm/1/

var text = "this is a dog called gav and a thing which is a folan here.";

var words = [
    {'badword':/dog/, 'goodword':'1'},
    {'badword':/gav/ , 'goodword':'5'},
    {'badword':/folan/ , 'goodword':':6'}
];

for(var i=0;i<words.length;i++){
    var word = words[i];
    text = text.replace(word.badword, word.goodword);
};

alert(text);

应输出类似...... this is a 1 called 5 and a thing which is a :6 here.

的内容