Kane Villeneuve
Kane Villeneuve

Reputation: 3

how can I use split to get image name from src in javascript

Using javascript I'm making (trying to) the fullres version of the image appear in the dialog popup when you click on the thumbnail.

I am trying to get my image name (face.jpg) out of (images/face.jpg) using the split method. Right now my javascript applies the text "lrg_" in front of "images/face.jpg" which works if my images folder was named "lrg_images" but I'd like to trim the src down to just "face.jpg" in order to access "lrg_face.jpg" inside of the images folder. I've spent 5 hours on this gallery issue and am running out of time. Any thoughts? Thanks all.

<div id="thumbs">
    <figure id="figure">
        <img src="images/face.jpg" alt="a tribalface">
        <img src="images/harley.jpg" alt="an image of Harley Quinn">
    </figure>
</div>

<dialog id="fullsize">
</dialog>

<script>    
const showPic = document.getElementById("fullsize");
figure.addEventListener("click", function(e){

let pic = e.target;
let imageSource = pic.href.split("")[1];
let picDescription = pic.alt;
let picName = pic.getAttribute("src");
showPic.innerHTML = "<figure><img src=lrg_"+picName+" alt></figure>";
showPic.show(); 
console.log(imageSource);
});
</script>

Upvotes: 0

Views: 2194

Answers (3)

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

Split and get the last element in the array:

const showPic = document.getElementById("fullsize");
figure.addEventListener("click", function(e) {

  let pic = e.target;
  let imagePathArry = pic.src.split("/"); //Split at '/'
  let imageSource = imagePathArry[imagePathArry.length - 1] //get element at last index
  let picDescription = pic.alt;
  let picName = pic.getAttribute("src");
  showPic.innerHTML = "<figure><img src=lrg_" + picName + " alt></figure>";
  //showPic.show();
  console.log(imageSource);
});
<div id="thumbs">
  <figure id="figure">
    <img src="images/face.jpg" alt="a tribalface">
    <img src="images/harley.jpg" alt="an image of Harley Quinn">
  </figure>
</div>

<dialog id="fullsize">
</dialog>

Upvotes: 0

Rocky Sims
Rocky Sims

Reputation: 3598

Looks like you need something like this.

var path = "full/path/to/images/face.jpg";
var pathParts = path.split("/");
var file = pathParts[pathParts.length - 1];
console.log(file);

Upvotes: 0

Hampus
Hampus

Reputation: 2799

You need to pass the char you want to split at.

var parts = picName.split("/")[1];
var name = parts[parts.length-1];

Upvotes: 0

Related Questions