Javascript搜索&如果找到匹配项,则替换为新字符串

时间:2012-12-05 15:40:39

标签: javascript

我想搜索地址字符串。

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

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

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

如果找到“northeast”,请将其替换为“NW”。

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

 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]);  
         }                        
 }

它没有做任何事情,我错过了什么?

5 个答案:

答案 0 :(得分:1)

var newAddress = oldAddress
                    .replace("Southeast", "SE")
                    .replace("Southwest", "SW")
                    .replace("Northeast", "NE")
                    .replace("Northwest", "NW");
$("#address").text(newAddress);

答案 1 :(得分: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;
});​

DEMO: http://jsfiddle.net/rKK89/1/

答案 2 :(得分: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>

请参阅 LIVE DEMO

答案 3 :(得分: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/

小提琴

答案 4 :(得分:0)

我不知道你要用这​​个[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]);  
         }                         
}