6 Ways To Get First Word Of a JavaScript String


Extracting first word from a JavaScript string is a common task.

This guide will show various techniques to achieve this. From basic string methods like split() and trim() to advanced regular expressions, common traps , and even a practice question; we’ve covered it all.

Lets dive in! 👨‍💻


Refresher: String and Array methods

Before we start getting the first word of a String in JavaScript, lets refresh important String and Array methods, with some code examples.

  1. String Methods:
    • split(): Splits a string into an array of substrings based on a specified separator.
    • trim(): Removes whitespace from both ends of a string.
    • slice(): Extracts a section of a string and returns it as a new string.
    • charAt(): Returns the character at a specified index in a string.
  2. Array Method:
    • shift(): Removes the first element from an array and returns that element. This is useful in handling the array output of the split() method.
  3. Code Examples:
    • Splitting a string: let words = "Hello world".split(" ");
    • Trimming a string: let trimmed = " Hello ".trim();
    • Slicing a string: let sliced = "Hello world".slice(0, 5);
    • Using charAt: let char = "Hello".charAt(1); // 'e'
    • Shifting an array: let firstWord = words.shift(); // 'Hello'

Ways to get the First Word of a JavaScript String

Lets see various techniques to convert JavaScript Null or Undefined to Zero. We’ll see from the most straightforward to the most concise implementations.

Using String.split() and Accessing the First Element

The String.split() method in JavaScript is used to split a string into an array of substrings based on a specified separator. To extract the first word from a string, you typically use a space character (" ") as the separator. Here’s how it works:

String split() (JavaScript)
let sentence = "Hello world!";
let words = sentence.split(" "); // Splits the string into words
let firstWord = words[0]; // Accesses the first word
console.log(firstWord); // Outputs: "Hello"

Common mistakes include not handling edge cases, like strings without spaces. In such cases, the entire string is returned as the first element of the array:

Split(), if no spaces (JavaScript)
let singleWord = "Hello";
let result = singleWord.split(" ");
console.log(result[0]); // Outputs: "Hello", since there are no spaces

So, split() will return an array, and accessing the first element gives the first word or the entire string if no separator is found. But this will fail if your string starts with a ” ” (space).

split() issue with leading space (JavaScript)
let sentence = " Hello world!";
let words = sentence.split(" ");
console.log(words[0]); // Outputs: "" (an empty string)

Here, you’ll need to trim the leading space in your string before split.

Using String.trim() with String.split()

trim() removes any leading and trailing white spaces from a string, ensuring that when you split the string, these spaces don’t affect the outcome.

In following example, we apply split() to a string with leading or trailing spaces. And if we access first element, then its not the first word. So we need to remove the leading spaces first, to ensure we get the first word as first element of the split string array.

String.trim() with String.split() (JavaScript)
// Without Trimming leading and trailing spaces:
let sentenceWithSpaces = "  Hello world!  ";
let wordsWithSpaces = sentenceWithSpaces.split(" ");
console.log(wordsWithSpaces);
// Output: [ '', '', 'Hello', 'world!', '', '' ]
console.log(wordsWithSpaces[0]);
// Outputs: "" (due to leading space)

// After Removing leading and trailing spaces:
let trimmedSentence = sentenceWithSpaces.trim();
console.log(trimmedSentence);
// Outputs: "Hello world!"
let words = trimmedSentence.split(" ");
console.log(words);
// Outputs: [ 'Hello', 'world!' ]
console.log(words[0]);
// Outputs: "Hello"

Using Array.shift() after splitting the String

The Array.shift() method is used to remove the first element from an array and return that element. This method can be particularly useful after splitting a string using String.split().

  • In following example, split() first divides the string into an array of words.
  • Then, shift() removes the first element of this array (the first word) and returns it.
  • The array words is now modified and no longer contains the first word.
Array.shift() after split (JavaScript)
let sentence = "Hello world! Have a nice day!";
// Split the sentence into words
let words = sentence.split(" ");
// Remove and get the first word from the array
let firstWord = words.shift();

console.log(firstWord);
// Outputs: "Hello"
console.log(words);
// Outputs the remaining words in the array: ["world!", "Have", "a", "nice", "day!"]

Using String.slice() and String.indexOf()

If you know your string definitely starts with a word (not empty space), then this 2 step method can be used.

  1. Find the Index of the First Space: Use String.indexOf() to find the position of the first space character in the string. If the string starts with a word (not a space), indexOf(" ") will return the end position of the first word.
  2. Slice the String to Extract the First Word: Use String.slice() to cut out the first word from the string. Start slicing from the beginning of the string (index 0) and go up to the index found by indexOf().

In following code, indexOf(" ") finds the space after “Hello”, and slice(0, firstSpaceIndex) extracts “Hello”. Specially useful for strings that start with a word. But if the string starts with a space, indexOf(" ") will return 0, and slicing will give an empty string.

String.slice() and String.indexOf() (JavaScript)
let sentence = "Hello world! Have a nice day!";

// Find the index of the first space
let firstSpaceIndex = sentence.indexOf(" ");
// Extract the first word
let firstWord = sentence.slice(0, firstSpaceIndex);

console.log(firstWord);
// Outputs: "Hello"

Using String.prototype.charAt() in loop

Using String.prototype.charAt(), iterate through each character of the string to check whether its a space or a non-space.

Let’s put this approach to test using two scenarios to extract first word: one where the string starts with a space and another where it doesn’t. And lets handle both in a single function extractFirstWord.

The function, first skips any leading spaces, then continues to extract characters until it encounters a space, which indicates the end of the first word. So it accurately extracts leading space.

String.prototype.charAt() (JavaScript)
function extractFirstWord(sentence) {
  let firstWord = "";
  let i = 0;

  // Skip leading spaces for strings that start with a space
  while (
    i < sentence.length &&
    sentence.charAt(i) === " "
  ) {
    i++;
  }

  // Extract the first word
  for (; i < sentence.length; i++) {
    if (sentence.charAt(i) === " ") {
      // Exit loop when the first non-leading space is found
      break;
    }
    firstWord += sentence.charAt(i);
  }

  return firstWord;
}

let sentenceWithSpace = " Hello world!";
let sentenceWithoutSpace = "Hello world!";
console.log(extractFirstWord(sentenceWithSpace));
// Outputs: "Hello"
console.log(extractFirstWord(sentenceWithoutSpace));
// Outputs: "Hello"

Using Regex with String.prototype.match()

Regular expressions (regex) are patterns used to match character combinations in strings, making them powerful for text processing. The String.prototype.match() method returns an array containing the entire match as the first element and the captured groups (in this case, the first word) as subsequent elements.

The following code uses a regular expression to find the first word in a string. The regex ^\s*(\w+) breaks down as follows:

  • ^ asserts the start of the string.
  • \s* matches any number of whitespace characters at the beginning of the string, if present.
  • (\w+) is a capture group that matches one or more word characters (letters, digits, or underscores). This is what captures the first word.

In the match array, match[0] is the full string that matches the regex, and match[1], match[2], etc., are the contents of the first, second, etc., capture groups. In our case, match[1] contains the first word of the string, which is what we’re interested in.

Regex & String.prototype.match() (JavaScript)
let sentence = "   Hello world! Have a nice day!";

// Regex to match the first word (even with leading space)
let regex = /^\s*(\w+)/;
let match = sentence.match(regex);

console.log(match);
// Output: [
//   '   Hello',
//   'Hello', 👈
//   index: 0,
//   input: '   Hello world! Have a nice day!',
//   groups: undefined
// ]

// Lets specifically print our Match.
if (match) {
    console.log(match[1]); // Outputs: "Hello"
} else {
    console.log("No match found");
}

Tips & Mistakes in Sorting JavaScript Maps

Handling Strings with No Spaces (Single Word Strings):

For strings without spaces, methods like split() will return the entire string as the first element of the resulting array. Ensure your code can handle such cases gracefully.

Single Word Strings (JavaScript)
let singleWord = "Hello";
console.log(singleWord.split(" ")[0]); 
// Outputs: "Hello"

Dealing with Empty Strings and Edge Cases

Empty strings or strings with only whitespace characters should be handled to avoid unexpected results.

Empty String (JavaScript)
let emptyString = "";
console.log(emptyString.split(" ")[0]); 
// Outputs: "" (empty string)

Handling Strings with Special Characters

Consider strings that may contain punctuation marks or special characters. These might need different handling depending on whether they are considered part of a word. Like, we can use Regex to filter out only alphabets. Regex ^[a-zA-Z]+ matches only alphabet characters from the start of the string, effectively ignoring any punctuation or special characters.

Special Characters (JavaScript)
let stringWithPunctuation = "Hello, world!";

// Using split - Fails to remove punctuation
let firstWordWithPunctuation = stringWithPunctuation.split(" ")[0];
console.log(firstWordWithPunctuation); 
// Outputs: "Hello," (includes comma)

// Using regex - Successfully extracts only alphabet characters
let regex = /^[a-zA-Z]+/;
let match = stringWithPunctuation.match(regex);
let firstWord = match ? match[0] : "No word found";
console.log(firstWord); 
// Outputs: "Hello" (without comma)

🧪Practice Coding Problem: Third Word Extractor

In the spirit of Test Driven Learning ( 😁), lets test our understanding by solving a problem.

Write a function that extracts every third word from a sentence. Should skip punctuation marks (from the word) and address edge cases, like sentences with fewer than three words or whitespace strings.

Problem (JavaScript)
function extractEveryThirdWord(sentence) {
  // > > > 👉 Write code here 👈 < < <
}

// Testing the function with various scenarios
console.log(extractEveryThirdWord(
  "One, two three! four five six? seven")); 
// "three six"

console.log(extractEveryThirdWord(
  "Hello world, this is a test sentence!")); 
// "this sentence!"

console.log(extractEveryThirdWord("  ")); 
// ""

console.log(extractEveryThirdWord("One two")); 
// ""
Please attempt before seeing the Answer:
Solution (JavaScript)
function extractEveryThirdWord(sentence) {
    // Handle empty or whitespace-only strings
    if (!sentence.trim()) return ""; 

    // Extract words, ignoring punctuation
    let words = sentence.match(/\b\w+\b/g);
    // Handle insufficient number of words
    if (!words || words.length < 3) return "";

    let result = [];
    for (let i = 2; i < words.length; i += 3) {
        result.push(words[i]);
    }
    return result.join(" ");
}

Explanation:

  • The function uses String.match() with a regex (/\b\w+\b/g) to extract words, discarding punctuation.
    • \b: A word boundary. This ensures that the match starts and ends at the boundary of a word, preventing partial word matches.
    • \w+: This matches one or more word characters (letters, digits, and underscores).
    • \b: Another word boundary, marking the end of the word.
    • /g: A global flag, allowing the regex to match all occurrences within the string, not just the first one.
  • It checks for empty strings and cases where there are fewer than three words.
  • The function then iterates through the array, extracting every third word.
  • Edge cases like mixed characters in words, empty strings, and insufficient words are handled to ensure robustness.

Now you are an expert in getting the first word of a String in JavaScript, and in various String and Array methods.

Keep learning, and keep coding! 🚀👨‍💻

Scroll to Top