yigitozmen
yigitozmen

Reputation: 957

remove left part of image srcs with javascript and regex

<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

Answers (3)

Wikiti
Wikiti

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

RomanPerekhrest
RomanPerekhrest

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

kind user
kind user

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

Related Questions