javascript: get word length

How to Get Word Length using JavaScript

Getting the length of a word is a common requirement in various JavaScript applications. Fortunately, JavaScript provides several built-in methods to get the length of a string or word.

Method 1: Using the length Property

The simplest way to get the length of a word is to use the built-in length property of a string.

const word = "hello";
const length = word.length;
console.log(length); // Output: 5

In the above code, we have defined a string named "word" and assigned it the value "hello". We then used the built-in length property of the string to get its length and stored it in a variable named "length". Finally, we printed the value of the "length" variable in the console.

Method 2: Using the split() Method

We can also use the split() method to convert a string into an array of words, and then get the length of the desired word using its index in the array.

const sentence = "The quick brown fox jumps over the lazy dog";
const words = sentence.split(" ");
const wordLength = words[2].length;
console.log(wordLength); // Output: 5

In the above code, we have defined a string named "sentence" and assigned it the value "The quick brown fox jumps over the lazy dog". We then used the split() method to split the sentence into an array of words using space as a delimiter. We stored the array in a variable named "words" and accessed the third word ("brown") using its index in the array. Finally, we used the length property to get the length of the word and printed it in the console.

Method 3: Using Regular Expressions

We can also use regular expressions to get the length of a word. We can use the match() method to match a word in a string using a regular expression and then get its length.

const sentence = "The quick brown fox jumps over the lazy dog";
const word = "brown";
const regex = new RegExp(word, "gi");
const matches = sentence.match(regex);
const length = matches[0].length;
console.log(length); // Output: 5

In the above code, we have defined a string named "sentence" and assigned it the value "The quick brown fox jumps over the lazy dog". We then defined a variable named "word" and assigned it the value "brown". We used the RegExp() constructor to create a regular expression that matches the word "brown" in a case-insensitive manner. We then used the match() method to find all the matches of the regular expression in the sentence and stored them in an array named "matches". Since we know that there is only one match for the word "brown", we accessed it using its index (0) and used the length property to get its length. Finally, we printed the length in the console.

These are some of the ways to get the length of a word using JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe