1

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.

1
  • huh, thanks to all. It looks like the regex solutions are the best in here. I don't know regex very well so your help is greatly appreciated. Thanks to all. Commented Aug 30, 2012 at 1:24

3 Answers 3

2

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_

Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.