get first word from a string in javascript

There are multiple ways to get the first word from a string in JavaScript:

  1. Using substr method:
index.tsx
const str = "Hello World";
const firstWord = str.substr(0, str.indexOf(' '));
console.log(firstWord); // Output: "Hello"
121 chars
4 lines
  1. Using split method:
index.tsx
const str = "Hello World";
const firstWord = str.split(' ')[0];
console.log(firstWord); // Output: "Hello"
107 chars
4 lines
  1. Using regex:
index.tsx
const str = "Hello World";
const firstWord = str.match(/^\w+/)[0];
console.log(firstWord); // Output: "Hello"
110 chars
4 lines

All these methods will give you the first word from a string in JavaScript.

gistlibby LogSnag