jQuery find and replace with key value arrays

2019-07-27 03:16发布

found this code for find and replace

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;
});

jQuery find and replace with arrays thanks to https://stackoverflow.com/users/1106925/squint

its really great but i would like to refactor to use a key value array

var fr ={ 
 "Rd" : "road",
 "St" : "Street",
 "Ave" : "Avenue",
 };

firly new to jQuery any help would be great

1条回答
迷人小祖宗
2楼-- · 2019-07-27 03:52

Try

var re = $.map(fr, function (v, k) {
    return {
        regex: new RegExp('\\b' + k + '\\b', 'g'),
        value: v
    };
});
jQuery('#colCenterAddress').val(function (i, val) {
    $.each(re, function (i, obj) {
        val = val.replace(obj.regex, obj.value);
    });
    return val;
});

Demo: Fiddle

查看更多
登录 后发表回答