Search code examples
htmlfragment-identifier

HTML: how to use a href to link to a file name that starts with # character


I have many text files, the name of which starts with # (hash) sign. It would be very cumbersome to rename the files.

If I try to link to the text files in an HTML file, using <a href="#example.txt"> the browser interprets the leading # character as a "fragment identifier".

My requirement is for the link to open the text file in the browser.

I have tried substituting the leading # character like this:

<a href="#35;example.txt"> 
<a href="#&23;example.txt">

but that does not work (the text file is not opened).

Is there an HTML work-around, or is JavaScript required for this?


Solution

  • Problem -

    href with a # in front of the file name fails to load the file. This is because you need to URL Encode the symbol.

    Solution -

    Use %23 which is the URL Encoding for #.

    Example -

    If you want to use an href to link a file named #test.html, you would do this -

    <a href="%23test.html">Click Me!</a>
    

    Recommendation -

    Do not use file names with # in the name.

    If you want to rename all of the files in the directory you are working in, here is a bash script that will do that for you.

    #!/bin/bash
    
    target="/home/user/directory/change/$1"
    for f in "$target"/*
    do
        letter=$(basename $f | cut -c1-1)
        if [ "$letter" == "#" ]; then
            withoutHash=$(basename $f | cut -c 2-)
            mv  $f $withoutHash
        fi 
    done
    

    This bash script should be easy to understand but there is surely some one liner on Stack Overflow. Try setting up a test directory and playing with it. You could pretty easily figure out how to traverse sub directories if needed.