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...
- capturing
100x100
greedily possible,(.*)
, group 1 - matching
100x100
- replacing captured group 1, using
$1
, adding256x256
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
Post a Comment