Trouble replacing middle of content with JavaScript regex? -
i have text
name[one][1][two][45][text]
i catch text "45" using pattern
/(.*?)rows\]\[([0-9]*)(.*)/; but how can replace 45 other digit? because if use same pattern replace method, replacing entrire previous word. code is
var name = "name[one][1][two][45][text]"; var pattern = /(.*?)two\]\[([0-9]*)(.*)/; var number = name.match(pattern); number = parseint(number[2]); var replacepattern = /(.*?)two\]\[([0-9]*)/; var newname = name.replace(replacepattern, parseint(number + 2)); console.log(newname); but it's returning 47][text]
but how can replace 45 other digit?
you can use replace function matching groups :
for example — here replace 45 7 :
"name[one][1][two][45][text]".replace(/(.*?)(two\]\[)([0-9]*)(.*)/,function (a,b,c,d,e){ // replace 7 want return b+c+'7'+e; }) result :
"name[one][3][two][7][text]" notice i've added () include other parts can later , add together.
edit: regarding actual example (+=2) : you can this :
return b+c+(parseint(d)+2)+e; -- actual example
Comments
Post a Comment