开发者

Cannot replace String portion based on Array in Javascript

开发者 https://www.devze.com 2023-03-13 00:53 出处:网络
I have two arrays, one is for a case and other one for b case. I want bodyTags string which consist one or more of different arr1 items to be replaced with items from arr2 with the same index.

I have two arrays, one is for a case and other one for b case. I want bodyTags string which consist one or more of different arr1 items to be replaced with items from arr2 with the same index.

Code below do开发者_StackOverflowesn't work. If you can fix it or advice me how to achieve desired effect with jQuery this will really help me out.

var arr1 = ["1a", "2a", "3a", "4a", "5a", "a6", "7a", "8a", "9a"];
var arr2 = ["1b", "2b", "3b", "4b", "5b", "6b", "7b", "8b", "9b"];

    var bodyTags = 'something a1 got funcky a6';

    for (var i = 0; i < arr1.length; i++) {
        bodyTags = bodyTags.replace(/arr1[i]/gi, arr2[i]);
    }


In the regular expression, arr1[i] will be taken literally. If you want to have dynamic expressions, you have to use RegExp:

bodyTags.replace(new RegExp(arr1[i],'gi'), arr2[i]);


May be this one?

for (var i = 0; i < arr1.length; i++) {
    myregexp = new RegExp(arr1[i], "gi");
    bodyTags = bodyTags.replace(myregexp, arr2[i]);
}


I believe this is what you need

var arr1 = ["1a", "2a", "3a", "4a", "5a", "a6", "7a", "8a", "9a"];
var arr2 = ["1b", "2b", "3b", "4b", "5b", "6b", "7b", "8b", "9b"];

var bodyTags = 'something 1a got funcky a6';

for (var i = 0; i < arr1.length; i++) {
    var re = new RegExp(arr1[i],"gi");
    bodyTags = bodyTags.replace(re, arr2[i]);
}

2 things:

  1. bodyTags contains a1 that is not in the first array
  2. The problem was that /arr1[1]/ is not looking for the value of arr[1] and concatenating it to the regexp its only hardcoding arr1[i] meaning that the regexp will match strings like 'arr1'
0

精彩评论

暂无评论...
验证码 换一张
取 消