user782104
user782104

Reputation: 13545

How to use jquery/javascript replace as preg_replace in PHP?

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

Upvotes: 1

Views: 5868

Answers (2)

Jason McCreary
Jason McCreary

Reputation: 72971

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.

Upvotes: 1

Amadan
Amadan

Reputation: 198324

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.

Upvotes: 4

Related Questions