Skip to content

Find repeated words in a string using JavaScript

In this tutorial we will learn how to find repeated words in a string using JavaScript. Let’s take this string as an example.

const str = "code code Hello Good Good morning. we Poop Code"

In the above string ‘code’ and ‘Good’ are repeated. To find this using JavaScript, we apply a regex to find repeated text and get an array of matches.

const str = "code code Hello Good Good morning. we Poop Code";
let matches = str.match(/\b(\w+)\b.*\b\1\b/g);
console.log(matches);

//["code code", "Good Good"]


console.log(matches.map(a=> a.split(" ")[0]));

//["code", "Good"]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.