2

I have three files: 'index.html', 'about.html' and 'contact.html'. I want to change the title using JS, according to their file name, although I know this is not the most efficient option.

I can't simply do: document.title = 'Home', because this will change the title of all the pages to 'Home'.

I tried to use if statements to change it, but it doesn't seem to work, although I am unsure whether I did this correctly:

if (file.name == 'index.html') {
    document.title = 'Home';
} else if (file.name == 'about.html') {
    document.title = 'About';
} else if (file.name == 'contact.html') {
    document.title = 'Contact';
}

If anyone has a good solution for this problem, it is greatly appreciated.

doelie247
  • 124
  • 8
  • 1
    Where does `file` come from? – j08691 Apr 21 '21 at 15:31
  • 1
    If you have 3 separate html files why not simply add a `` tag (AKA "The old fashioned way!). Why are you trying to do this with javascript in the first place? – Jamiec Apr 21 '21 at 15:41
  • https://stackoverflow.com/questions/16611497/how-can-i-get-the-name-of-an-html-page-in-javascript/21343880 – epascarello Apr 21 '21 at 15:42

1 Answers1

2

Maybe you could do something like this :

document.title = file.name.charAt(0).toUpperCase() + name.replace(/\.[^/.]+$/, "").slice(1)

(toUpperCase capitalizes the first character of the name, and the regex takes care of removing the extension)

Anchorwave
  • 66
  • 1
  • 6