regex - JavaScript negative lookahead regular expression producing wrong result -


assume following url: http://a2.mzstatic.com/us/ryoyo0/078/purple100x100/v4/38/e3/b4/38e3b4a2-b422-8d1e-69f2-593fc035c9d4/mzl.vqhwzhhc.100x100-75.jpg

we want replace last occurrence of 100x100 256x256. url should read:

http://a2.mzstatic.com/us/ryoyo0/078/purple100x100/v4/38/e3/b4/38e3b4a2-b422-8d1e-69f2-593fc035c9d4/mzl.vqhwzhhc.256x256-75.jpg 

here's our javascript replace method:

replace( /100x100(?!100x100)/, '256x256' ) 

unfortunately, consistently replace first, not last, occurrence.

what doing wrong?

thanks!

another way it...

replace( /(.*)100x100/, '$1256x256' ) 

works by...

  1. capturing 100x100 greedily possible, (.*), group 1
  2. matching 100x100
  3. replacing captured group 1, using $1 , adding 256x256 in place of non-captured match

n.b. method can work last match (or first if make initial capture un-greedy adding ? after .*)

it avoid using look-around assertions, performance reasons, compatibility various regex implementations, , believe readability.

edit: test script

var url = "http://a2.mzstatic.com/us/ryoyo0/078/purple100x100/v4/38/e3/b4/38e3b4a2-b422-8d1e-69f2-593fc035c9d4/mzl.vqhwzhhc.100x100-75.jpg"  console.log(url.replace(/(.*)100x100/, '$1256x256'))  // output: // http://a2.mzstatic.com/us/ryoyo0/078/purple100x100/v4/38/e3/b4/38e3b4a2-b422-8d1e-69f2-593fc035c9d4/mzl.vqhwzhhc.256x256-75.jpg 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -