Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find and replace with arrays

Tags:

arrays

jquery

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?

like image 728
champton Avatar asked Jan 16 '12 14:01

champton


1 Answers

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

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/


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/

like image 133
3 revsuser1106925 Avatar answered Sep 23 '22 06:09

3 revsuser1106925