Changing the title based on the file name

Viewed 354

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.

1 Answers

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)

Related