I have a website page with a three words title. how can I create a variable in Javascript that outputs only the first word of that title ?
thanks for your help !
I have a website page with a three words title. how can I create a variable in Javascript that outputs only the first word of that title ?
thanks for your help !
There are a lot of way to do that. If you have these words separated by space, the simplest and straightforward you can write the following:
const firstWord = pageTitle.split(' ')[0];
If you need to extract page title from browser API, just address document.title
and use it as pageTitle
variable.
const firstWord = document.getElementsByTagName('title')[0].innerText.split(' ')[0]
Description:
docuemnt.getElementsByTagName('tagName')
finds all the elements with the given tagName. We want only only the first element of it. Hence add put [0]
next to it.
innerText
gives the content of the given element.
split(" ")
splits the given string into an array based on the argument. Here since we want to split into words, we use empty space ' '
. Since we need only the first word, you have to again use [0]
If you need the first "word" of the title, you can:
document.title
Note: You do not need to use the global flag for the expression, because we only care about the left-hand side of the split.
const firstWordOfTitle = document.title.trim().split(/\s+/).shift();
console.log(`First word of document: "${firstWordOfTitle}"`); // "Test"
<title>Test Title</title>