7

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?

2
  • 2
    That works in PHP, but unfortunately not in JavaScript. Commented Jan 16, 2012 at 14:35
  • That is not a valid javascript invocation of replace. It's not particularly internationalisable. It's client side work, which is easily circumvented. You need to ensure that each match is preceded by whitespace and succeeded by a non word character. Commented Jan 16, 2012 at 14:36

3 Answers 3

14

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/

Sign up to request clarification or add additional context in comments.

Comments

0

One way to do this, is to loop through the val string, and if you see a word in the f array, replace it with its counterpart in the r array.

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

Comments

0
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.