Reputation: 957
<img src="../public/images/pages/contact-685px_06.jpg" height="170" width="685"/>
i want to remove left part of src which starts with public.
this is the code i tried:
$(this).attr("src", $(this).attr("src").replace("../public", ""));
but this doesn't fit for all situations. because it is static. only removes ../public part. there is no standart for paths. for example: it may be ../../public instead of ../public or etc... (it may tend to left)
Upvotes: 0
Views: 54
Reputation: 1636
Use a regular expression instead of a string. The regular expression you want is "match (pairs of dots) subpaths until the public subpath is found". It can be implemented like this:
regex = /^(?:\.\.\/)+public\//
Applied to your code, in the replace
function, will result into this:
$(this).attr(
"src",
$(this).attr("src").replace(/^(?:\.\.?\/)+public\//, "")
);
Upvotes: 0
Reputation: 92854
Use the following approach:
var imgEl = $('img');
imgEl.attr("src", imgEl.attr("src").replace(/^.+public/, ""));
console.log(imgEl.attr("src"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="../public/images/pages/contact-685px_06.jpg" height="170" width="685"/>
Upvotes: 0
Reputation: 41893
If you want to remove everything on the left from public
keyword (including it), use:
str.replace(/.+public/, '')
var str1 = "./public/images/pages/contact-685px_06.jpg";
var str2 = "/awdawd/awd/public/images/pages/contact-685px_06.jpg";
var str3 = "even/mor3/@#4#%stuff/awdawd/awd/public/images/pages/contact-685px_06.jpg";
console.log(str1.replace(/.+public/, ''));
console.log(str2.replace(/.+public/, ''));
console.log(str3.replace(/.+public/, ''));
Upvotes: 2