JQuery find and replace arrays

I need to find the input value for all street abbreviations and replace it with the 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?

+6
source share
3 answers

You need to iterate the array f and try each replacement 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 what you are going to do on a regular basis, you might want to save arrays and even create a third array with pre-created 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/

+11
source
 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 can always return the array back to the string to return if you want.

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

0
source

One way to do this is to iterate over the string val , and if you see a word in array f , replace it with your instance in array 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(' '); }); 
0
source

Source: https://habr.com/ru/post/906116/


All Articles