jQuery的查找并替换数组 [英] jQuery find and replace with 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);
});
思考?
推荐答案
您需要遍历˚F
阵列,并尝试每个单独更换。
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/
如果这是你要定期做一些事情,你可能希望存储阵列,甚至使具有pre-做定期的前pressions第三阵列。
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/
这篇关于jQuery的查找并替换数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文