jQuery 查找并替换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8881436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:11:41  来源:igfitidea点击:

jQuery find and replace with arrays

jqueryarrays

提问by champton

I need to search an input's value for all street abbreviations and replace with appropriate suffix. This is what I have so far:

我需要搜索所有街道缩写的输入值并替换为适当的后缀。这是我到目前为止:

jQuery('#colCenterAddress').val(function(i,val) {
    var f = ['Rd','St','Ave'];
    var r = ['Road','Street','Avenue'];
    return val.replace(f,r);
});

Thoughts?

想法?

回答by

You need to iterate the fArray, and try each replace separately.

您需要迭代f数组,并分别尝试每个替换。

jQuery('#colCenterAddress').val(function(i,val) {
    var f = ['Rd','St','Ave'];
    var r = ['Road','Street','Avenue'];
    $.each(f,function(i,v) {
        val = val.replace(new RegExp('\b' + v + '\b', 'g'),r[i]);
    });
    return val;
});

DEMO:http://jsfiddle.net/vRTNt/

演示:http : //jsfiddle.net/vRTNt/



If this is something you're going to do on a regular basis, you may want to store the Arrays, and even make a third Array that has the pre-made regular expressions.

如果这是您要定期执行的操作,您可能希望存储数组,甚至创建具有预制正则表达式的第三个数组。

var f = ['Rd','St','Ave'];
var r = ['Road','Street','Avenue'];

var re = $.map(f, function(v,i) {
    return new RegExp('\b' + v + '\b', 'g');
});

jQuery('#colCenterAddress').val(function(i,val) {
    $.each(f,function(i,v) {
        val = val.replace(re[i],r[i]);
    });
    return val;
});

DEMO:http://jsfiddle.net/vRTNt/1/

演示:http : //jsfiddle.net/vRTNt/1/

回答by RonnyKnoxville

var valArray = val.split(" ");

for(x = 0; x < valArray.length; x++){
    for(y = 0; y < r.length; y ++){
        if (valArray[x] == f[y]){
            valArray[x] = r[y];
        } 
     }
}
return valArray

You could always turn the array back into a string for the return if you like.

如果您愿意,您始终可以将数组转换回字符串以供返回。

Demo:http://jsfiddle.net/vRTNt/12/

演示:http : //jsfiddle.net/vRTNt/12/

回答by Rocket Hazmat

One way to do this, is to loop through the valstring, and if you see a word in the farray, replace it with its counterpart in the rarray.

一种方法是循环遍历val字符串,如果您在f数组中看到一个单词,请将其替换为r数组中的对应词。

jQuery('#colCenterAddress').val(function(i,val) {
    var f = ['Rd','St','Ave'];
    var r = ['Road','Street','Avenue'];
    var valArray = val.split(' ');
    $.each(valArray, function(i,v){
       var inF = $.inArray(v, f);
       if(inF !== -1){
         valArray[i] = v.replace(f[inF], r[inF]);
       }
    });
    return valArray.join(' ');
});