skip to Main Content

Currently I am making a game, and I want to check if my html element 'document.getElementById("terminal").src' is equal to "sprites/terminal.png"….
Because I use a live server via visual studio code, the "document.getElementById("terminal").src" is actually equal to 'http://127.0.0.1:5500/sprites/terminal.png'. Is there a way to change this or at least shorten the '.src' to exclude 'http://127.0.0.1:5500', and just be 'sprites/terminal.png'.
Thanks

4

Answers


  1. You can take a look on
    Get relative URL from absolute URL
    For a general URL extraction.

    in your case, you can also do the follow:

    document.getElementById("terminal").src.replace(window.origin, '')
    

    which will return the path without the origin, then you can assign it back to the src:

    const terminalDOM = document.getElementById("terminal");
    terminalDOM.src = terminalDOM.src.replace(window.origin, '')
    
    Login or Signup to reply.
  2. I think the most certain result would be received by using URL() constructor:

    const { src = ''} = document.getElementById('terminal');
    const path = new URL(src).pathname;
    
    console.log(path);
    <img id='terminal' src='http://127.0.0.1:5500/sprites/terminal.png' alt='terminal' />
    Login or Signup to reply.
  3. You can use the URL class in JavaScript to get the pathname.

    const image_source = document.getElementById("terminal").src;
    const url = new URL(image_source);
    console.log(url.pathname); //Output: '/sprites/terminal.png'
    
    // if you want to skip the first slash, you can use substring
    console.log(url.pathname.substring(1)); //Output: 'sprites/terminal.png'
    
    Login or Signup to reply.
  4. Instead of the src property, you could also check the src attribute, which the browser does not rewrite to an absolute URL so it will be exactly as in the HTML source:

    if (document.getElementById("terminal").getAttribute('src') === 'sprites/terminal.png') {
      // Do stuff
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search