1

我想搜索地址字符串。

如果找到“ Southeast”,则将其替换为“ SE”;

如果找到“西南”,则将其替换为“西南”;

如果找到“东北”,则将其替换为“NE”;

如果找到“东北”,则将其替换为“西北”。

这是我到目前为止所做的:

 var searchStr = [" Southeast ", " Southwest ", " Northeast ", " Northwest "];
 var replaceStr = [" SE ", " SW ", " NE ", " NW "];
 var oldAddress = $("#address").text();

 for (i=0;i<searchStr.length;i++){
     var n = oldAddress.match(/this[i]/g);
         if(n != null){
            $("#address").text(replaceStr[i]);  
         }                        
 }

它什么也没做,我错过了什么吗?

4

5 回答 5

1
var newAddress = oldAddress
                    .replace("Southeast", "SE")
                    .replace("Southwest", "SW")
                    .replace("Northeast", "NE")
                    .replace("Northwest", "NW");
$("#address").text(newAddress);
于 2012-12-05T15:47:33.327 回答
1
$("#address").text(function(i, text) {
    $.each({
        "Southeast": "SE",
        "Southwest": "SW",
        "Northeast": "NE",
        "Northwest": "NW"
    }, function(k, v) {
        var regex = new RegExp('" ' + k + ' "', "ig");
        text = text.replace(regex, '" ' + v + ' "');
    });
    return text;
});​

演示:http: //jsfiddle.net/rKK89/1/

于 2012-12-05T15:47:46.153 回答
0

除了现有的答案,你也可以这样做: -

 var searchStr = [" Southeast ", " Southwest ", " Northeast ", " Northwest "];
 var replaceStr = [" SE ", " SW ", " NE ", " NW "];
 var oldAddress = $("#address").text();

 for (i=0;i<searchStr.length;i++){
     oldAddress = oldAddress.replace(searchStr[i], replaceStr[i]);
 }
 $("#replaced").text(oldAddress);

示例 HTML:

<div id="address">First I went to Southeast , next to Northwest , next to Southwest and finally to Northeast </div>
<br/>
Updated content is here:
<br/>
<div id="replaced"></div>

参考现场演示

于 2012-12-05T16:03:48.033 回答
0
 var r = {
   southeast: 'SE',
   southwest: 'SW',
   northeast: 'NE',
   northwest: 'NW'
 };

 $("#address").text ($("#address").text().replace (
   RegExp (Object.keys (r).join ('|'), 'ig'), 
   function (m) { return r[m.toLowerCase ()]; }));​

请参阅http://jsfiddle.net/fJ7Vf/上的小提琴

于 2012-12-05T16:04:44.697 回答
0

我不知道你想用 this[i] 做什么,但即使你在那个地方写 searchStr[i] 它也行不通。因为您正在那里创建一个字符串。为了使其工作,您需要创建一个正则表达式对象

试试这个代码

var searchStr = [" Southeast ", " Southwest ", " Northeast ", " Northwest "];
var replaceStr = [" SE ", " SW ", " NE ", " NW "];
var oldAddress = $("#address").text();

for (var i=0;i<searchStr.length;i++){
var pattern =new RegExp(searchStr[i]);
    var n = oldAddress.match(pattern);
       if(n != null){
            $("#address").text(replaceStr[i]);  
         }                         
}
于 2012-12-05T16:05:22.557 回答