How to use indexOf method In Javascript
- In this approach, we are using the indexOf method to check if the current word appears again later in the array of words.
- If it does, the word is identified as the first repeated word; otherwise, the result remains “No Repetition”.
Example: The below example uses indexOf to Find the first repeated word in a string.
let str = "Ravi had been saying that he been there";
let words = str.split(" ");
let res = "No Repetition";
for (let i = 0; i < words.length; i++) {
if (words.indexOf(words[i]) !== i) {
res = words[i];
break;
}
}
console.log(res);
Output:
been
Time Complexity: O(n^2), where n is the number of words in the input.
Space Complexity: O(1)
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string.
Examples:
Input: “Ravi had been saying that he had been there”
Output: had
Input: “Ravi had been saying that”
Output: No Repetition
Below are the approaches to Finding the first repeated word in a string:
Table of Content
- Using Set
- Using indexOf method
- Using Nested for loop
- Using a Map
- Using an Object