-1

有多个 if 条件执行用字符串 KAP 替换字符串:

var nameList = $('#name').text();

if(nameList.indexOf('SAM') > -1){
    var newName = nameList.replace(/SAM/g, 'KAP');
    $('#name').html(newName);
}

if(nameList.indexOf('PAT') > -1){
    var newName = nameList.replace(/PAT/g, 'KAP');
    $('#name').html(newName);
}

如果我们的数组中已经存在新名称,如何使用 jquery/javascript 将上述两个压缩为一个 if 条件,如下所示

var nameArray = ['SAM','PAT','DAB'];

这样,如果在 nameList 中找到上述任何一项,则不会检查其他条件。

4

4 回答 4

1
var nameList = $('#name').text();

var nameArray = ['SAM','PAT','DAB'];
nameArray.some(function(name) {
    if (!!~nameList.indexOf(name)) {
        nameList.replace(new RegExp(name, 'gi'), 'KAP');
        return true;
    }
    return false;
});

Array.some 方法遍历数组的元素,直到函数返回 true。查看Mozilla 开发者文档

!!~ 是操作数的组合,它只使 -1 为假。

于 2013-11-14T19:21:48.627 回答
0

您不需要任何 if/else 语句 - 您只需使用正则表达式

var nameArray = ['SAM','PAT','DAB'];// your list of words
var nameList = $('#name').text();// your string to check
var reg = new RegExp(nameArray.join('|'),"g");// create the regex object - reg == /SAM|PAT|DAB/g
$('#name').html(nameList.replace(reg,'KAP'));

小提琴

于 2013-11-14T19:38:25.913 回答
0

在最基本的情况下,我建议:

var nameArray = ['SAM','PAT','DAB'],
    reg = new RegExp('(' + nameArray.join('|') + ')', 'i'),
if (reg.test(nameList)) {
    // one of those names was found
}
else {
    // none of those names were found
}

简化的 JS Fiddle 演示

于 2013-11-14T19:11:18.257 回答
0

干得好:

JS 小提琴:http: //jsfiddle.net/2F4dG/2/

HTML

<div id="name">Hi my name is Sam. Sam is cool.</div>

代码

$(function(){
    var nameList = $('#name').text()

    var nameArray = ['SAM','PAT','DAB'];

    //loop through all possible names
    for(var i=0;i<nameArray.length;i++){
        if(nameList.toUpperCase().indexOf(nameArray[i])!=-1){
            //new regex out of name we are replacing...
            var re = new RegExp(nameArray[i],"gi");
            //replacae all matches
            var newName = nameList.replace(re,"KAP");
            //set new name
            $('#name').html(newName);
            //exit loop we found our match...
            break;
        }
    }
});

输出

Hi my name is KAP. KAP is cool.

于 2013-11-14T19:24:51.600 回答