Im using .replace() with jQuery to remove different strings from an img URL:
src = src.replace("/_w", "");
src = src.replace("_jpg", "");
src = src.replace("_jpeg", "");
src = src.replace("_png", "");
src = src.replace("_gif", "");
As you can see its pretty primative and not very clever, is there anyway I can replace this with something a little more elegant.
Essentially the url will always be 1 of the following:
http://local.com/images/_w/image_jpg.jpg
http://local.com/images/_w/image_jpeg.jpeg
http://local.com/images/_w/image_png开发者_StackOverflow.png
Is there anyway I can write a .replace() to remove the /_w/ then remove all characters between the last '.' in the URL and the last underscore?
not tested - but I think this should do it
src = src.replace(/\/_w|_jpg|_png|_gif/g,'')
or better still...
src = src.replace(/\/_w(.+?)_(jpg|png|gif)\./,"$1.")
which matches /w, then stores all characters up to _gif or _jpg etc... then replaces everything captured with what was stored (followed by a dot).
Regular expressions are your friend.
If it's really safe to replace everything between /_w
and .
every time you can use:
src = src.replace(/\/_w[^.]*/,'');
If you become familiar with the basics of regex it will save you time on countless problems. It's an incredibly versatile tool.
A good reference
A Regex tester
精彩评论