0

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 !

  • Does this answer your question? [javascript break sentence by words](https://stackoverflow.com/questions/18473326/javascript-break-sentence-by-words) – Harun Yilmaz Jun 01 '20 at 12:05

3 Answers3

0

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.

0
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]

Pardhu
  • 5,935
  • 2
  • 11
  • 23
  • Sometimes page titles have extra spacing... I would be safe and just use: `document.title.trim().split(/\s+/).shift()` (no need for global pattern). – Mr. Polywhirl Jun 01 '20 at 15:25
0

If you need the first "word" of the title, you can:

  1. Access the document.title
  2. Trim any unnecessary white-space
  3. Shift the resulting array to grab the first sequence of non-white-space characters

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>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132