Craig Pelkie
Craig Pelkie

Reputation: 13

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?

Upvotes: 1

Views: 1908

Answers (3)

Pradyumna Hebbar
Pradyumna Hebbar

Reputation: 1

You have to remove the # in your fileNames. # means an id and the browser thinks its an id and looks for it on the page.

Upvotes: -1

wuno
wuno

Reputation: 9875

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.

Upvotes: 2

FilipA
FilipA

Reputation: 612

If you really need to do it you can try with replacing "#" with %23. It should work.

You will avoid lots and lots and lots of pain if you are able to rename your files so they don't contain a "#" character.

As long as they do, you will probably have current and future cross-browser issues, confusion on behalf of future developers working on your code (or confusion on your behalf in the future, when you've forgotten the ins and outs of the encoding), etc.

Also, some Unix/Linux systems don't allow "#" in filenames. Not sure what OS you're using, but your filenames should be as portable as possible across OSs, even if you're "sure" right now that you'll never be running on one of those systems.

Upvotes: 2

Related Questions