Search code examples
javascriptjqueryimagesrc

Remove First Forward Slash from IMG SRC


I have an image tag..

<img src="/folder1/folder2/image.jpg">

I need to, using javascript / query remove the first forward slash from the src tag to make the image tag like this.

<img src="folder1/folder2/image.jpg">

I would like to do this for any image on the page.

Any thoughts?

Justin


Solution

  • Tested and works:

    $('img').each(
        function(){
            var src = $(this).attr('src');
            if (src.indexOf('/') === 0){
                this.src = src.replace('/','');
            }
        });
    

    JS Fiddle demo.

    As per nnnnn's suggestion, in comments below, an alternative solution using substring():

    $('img').each(
        function(){
            var src = $(this).attr('src');
            if (src.indexOf('/') === 0){
                this.src = src.substring(1);
            }
        });
    

    JS Fiddle demo.

    Note that I'm using:

    var src = $(this).attr('src');
    

    because I want the actual contents of the attribute, rather than the browser's evaluated interpretation of that attribute (for example with src="/folder1/folder2/image.jpg" on jsFiddle this.src returns http://fiddle.jshell.net/folder1/folder2/image.jpg).