I am trying to get my picture's SRC path file link
At the moment my code looks like this
picture.addEventListener("click", (e) => {
console.log(e.target.src)
})
This prints something like this
http://127.0.0.1:5500/img/code-mobile.png
And what I really want is just the bit that looks like
/img/code-mobile.png
How can I achieve this?
picture.addEventListener("click", (e) => {
console.log(new URL(e.target.src).pathname)
})
You can use the URL
class to parse the URL for you:
picture.addEventListener("click", (e) => {
var url = new URL(e.target.src);
console.log(url.pathname);
})
To get the relative path instead of the absolute one, use getAttribute('src') instead of src in your code.
You can get the host string from window.location.host
and then replace it with an empty string in the url.
something like:
picture.addEventListener("click", (e) => {
let imageSrc = e.target.src.replace(window.location.href,'');
console.log(imageSrc);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.