user782104 user782104 -3 years ago 204
Javascript Question

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

Answer Source

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download