Why doesn't my javascript regexp work with array items?

Scott Pendleton
var x = new Array('1','2','3');
var y = new Array('a','b','c');
var iLen = x.length;
var s = 'abcdefgabcdefg';

for (var i=0;i<iLen;i++) {
   var re = new RegExp(x[i],'g');
   s = s.replace(y[i], re);
}

alert(s);

I want the result to be 123defg123defg. Instead, I get /1/g/2/g/3/gdefgabcdefg.

Mritunjay

You are doing it wrong, because you want to replace occurrences of array y to occurrences of x globally, you should say like

for (var i=0;i<iLen;i++) {
   var re = new RegExp(y[i],'g'); //this is regexp for global y[i]
   s = s.replace(re, x[i]); //replace all occurrences of y[i] with x[i]
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Why doesn't my homemade isset function in javascript completely work?

분류에서Dev

Why doesn't my SetLength work?

분류에서Dev

Why doesn't my iptables rule work?

분류에서Dev

Why doesn't my .desktop file work?

분류에서Dev

JavaScript array["index"].push() doesn't work

분류에서Dev

Why won't this regexp in htaccess work properly?

분류에서Dev

Why switch case in javascript doesn't work with string on Microsoft Edge?

분류에서Dev

Why isEOF doesn't work?

분류에서Dev

Why json doesn´t work?

분류에서Dev

Why doesn't isdigit() work?

분류에서Dev

PHP Array doesn't show all items

분류에서Dev

My validation doesn't work for textarea

분류에서Dev

My button used to work -- but now it doesn't

분류에서Dev

`__call` doesn't work in my Lua code

분류에서Dev

My PHP array somehow doesn't see my array as an array

분류에서Dev

Array variables and constructors - why my code no work?

분류에서Dev

Why doesn't this array formula work when cell reference contains a formual?

분류에서Dev

Why doesn't LibreOffice work with the HUD?

분류에서Dev

Why wmctrl doesn't work for certain windows?

분류에서Dev

Why doesn't this math work with macros?

분류에서Dev

Why doesn't beep work in Ubuntu?

분류에서Dev

why the click() function doesn't work?

분류에서Dev

Why doesn't this simple enable_if work?

분류에서Dev

Why doesn't this Mongoose query work?

분류에서Dev

Why this jQuery doesn't work in Codeigniter?

분류에서Dev

Why doesn't source lib/* work?

분류에서Dev

Jquery Why doesn't toggleClass work here?

분류에서Dev

Why char[] work,but char * doesn't

분류에서Dev

why doesn't history work in Ubuntu?