javascript - Replace string between second set of [ and ] -


i learning regex, , got doubt. let's consider

var s = "yyyn[1-20]n[]nyy"; 

now, want replace/insert '1-8' between [ , ] @ second occurrence. output should be

yyyn[1-20]n[1-8]nyy  

for had tried using replace , passing function through shown below:

var nth = 0; s = s.replace(/\[([^)]+)\]/g, function(match, i, original) {     nth++;     return (nth === 1) ? "1-8" : match; }); alert(s); // wont work 

i think regex not matchiing string using. how can fix it?

you regex \[([^)]+)\] not match empty square brackets since + requires @ least 1 character other ). guess wanted write \[[^\]]*\].

here fix solution:

var s = "yyyn[1-20]n[]nyy";  var nth = 0;  s = s.replace(/\[[^\]]*\]/g, function (match, i, original) {      nth++;      return (nth !== 1) ? "[1-8]" : match;  });  alert(s);

here way of doing it:

 var s = "yyyn[1-20]n[]nyy";  var nth = 0;  s = s.replace(/(.*)\[\]/, "$1[1-8]");  alert(s);

the regex (.*)\[\] matches , captures group 1 greedily text possible (thus last set of empty []), , matches empty square brackets. restore text before [] $1 backreference , add out string 1-8.


Comments