I have this image url: http://files.myweb.com/12/06/002_xz808/normal_paris_01.jpg
I need to get this http://files.myweb.com/12/06/002_xz808/paris_01.jpg
I can't use simple replace function on "normal_"
because this keyword can accidentaly appear before filename in its path. I need to use it for THE LAST "normal_"
but I don't know how. Please help.
Hope this helps:
function replNormal(normal) {
return normal.replace(/^(.*)normal\_(.*?)$/, '$1$2');
}
console.log(replNormal("http://files.myweb.com/12/06/normal_002_xz808/normal_paris_01.jpg"));
The capture groups in the prior regular expression (the parts in parenthesis) are greedy and then lazy.
The greedy one (.*) wants to expand as far as it can, before it stops capturing.
The lazy one (.*?) wants to quit as quickly as it meets it's capture requirements.
The back references in the replacement string tell it to concatenate what it finds in the first and second capture groups directly together, skipping the non-captured normal_
There are many ways to go about this. The first that comes to mind is to split the URL on /
, and do the replacement in the last component, then join it back together:
var url = 'http://files.myweb.com/12/06/002_xz808/normal_paris_01.jpg';
var parts = url.split('/');
// Remove the last part, everything following the last /
// and do the replacement
var img = parts.pop().replace("normal_", "");
// Stick the new string back onto the array
parts.push(img)
// And put all the / back in...
url = parts.join("/");
console.log(url);
// "http://files.myweb.com/12/06/002_xz808/paris_01.jpg"
You can match the "/normal_" only in the last segment of the path like this:
var url = "http://files.myweb.com/12/06/002_xz808/normal_paris_01.jpg";
url = url.replace(/\/normal_([^\/]+)$/, "\/$1");
Working demo: http://jsfiddle.net/jfriend00/rzj8u/
This will only replace "normal_" in the last segment of the URL (no slashes after it).