1

The preg_replace function in PHP provides a limit parameter. For instance, the first occurrence of medium replace with original, and the second occurrence of medium replace with "type".

$path = "demo\/medium\/Web081112_P001_medium.jpg";
$path = preg_replace ("/medium/","original",$path,1);
$path = preg_replace ("/medium/","type",$path,2);
echo $path;
// output : demo\/original\/Web081112_P001_type.jpg

So, are there any way using JQuery/ JavaScript to implement similar function? Thanks

4
  • That 2 doesn't do what you think it does... the first occurrence has already been replaced by that time. Commented Dec 10, 2012 at 2:21
  • 4
    You don't use jQuery for string manipulation. Vanilla JS is a much better choice. Commented Dec 10, 2012 at 2:30
  • @nnnnnn: OMG, haven't seen that link yet, that's hilarious! :D Commented Dec 10, 2012 at 2:31
  • @Amadan - Yes, it's awesome. Did you notice you can select the features you want and download a custom JS include file? I think the site's only been around since the middle of this year - I'd love to know if somebody on SO is responsible; they should get a one-off platinum JS badge for it or something... Commented Dec 10, 2012 at 2:51

2 Answers 2

4

General solution:

var n = 0;
"a a a a a".replace(/a/g, function(match) {
  n++;
  if (n == 2) return "c";
  if (n == 3 || n == 4) return "b";
  return match;
})
// => "a c b b a"

Also, you are mistaken: the second replacement will not happen. Limit 2 doesn't say "second occurence", it says "two occurences"; however, after the first preg_replace you don't have two mediums any more, so the second preg_replace ends up replacing the single one that is left, and then quits in frustration. You could do the same using two single-shot (non-global) replace (or preg_replace) invocations, without using any limit.

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

2 Comments

Seems like quite the long way around.
Cool, solution works! JavaScript is so unexpected and funny :)
1

are there any way using jquery/ javascript to implement similar function?

Use JavaScript's native replace().

By default, replace() will only replace the first occurrence - unless you set the g modifier.

Example:

path = "demo/medium/Web081112_P001_medium.jpg";
path = path.replace("/medium/", "original");
path = path.replace("medium", "type");

Note: Your code doesn't match your specification. I addressed your specification.

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.