Apostolos
Apostolos

Reputation: 598

Find index of given words into phrase

I have the Example "this is another sunny day this month" and let's say two words, which call Phrase, "this month". The problem I have to resolve is to find in Example ALL the places of each word of the Phrase. So, I would expect as Index 0, 5, 6. Here is what I do: I split Example and Phrase into single words, I put them in two arrays and then I run the loop. But the output is not what I expect it to be. The idea of wrapping each word in a span is of Terry Morse (https://stackoverflow.com/users/3113485/terrymorse), see question How to change color of a word in a sentence by clicking it on PC or by touching it on Android. Could someone help me ?

<p id="hExample">this is another sunny day this month</p>
<p id="hPhrase">this sunny</p>
<p id="Indexes"></p>


const hExample = document.getElementById('hExample');
// Split into array of words
let jExample = hExample.innerHTML;
let ExampleWords = jExample.split(" ");

// wrap each word in a span
let ExampleContent = "";
for (const word of ExampleWords) {
    ExampleContent += `<span>${word}</span> `;
}

// add all spans to hExample
hExample.innerHTML = ExampleContent;

const hPhrase = document.getElementById('hPhrase');
// Split into array of words
let jPhrase = hPhrase.innerHTML;
let PhraseWords = jPhrase.split(" ");

// wrap each word in a span
let PhraseContent = "";
for (const word of PhraseWords) {
    PhraseContent += `<span>${word}</span> `;
}

// add all spans to hPhrase
hPhrase.innerHTML = PhraseContent;




var Indexes = getAllIndexes(hExample.innerHTML, hPhrase.innerHTML);

function getAllIndexes(arr, val) {
    var Indexes = [], i;

    for (i = 0; i < arr.length; i++) {
        for(k = 0; k < val.length; k++) {
            if (arr[i] === val[k]) {
                Indexes.push(i);
            }
        }
    }
    return Indexes;
}

document.getElementById("Indexes").innerHTML = Indexes;

Upvotes: 0

Views: 121

Answers (1)

Alex V
Alex V

Reputation: 216

I'm not sure what you meant by wrapping into spans, but your initial problem can be solved like this:

const phrase = "this is another sunny day this month";
const wordsToFind = "this month";
const wordsArr = wordsToFind.split(' ');
const indexes = [];

phrase.split(' ').forEach((word, index) => {
  if (wordsArr.includes(word)) {
    indexes.push(index);
  }
});

console.log(indexes);

const phraseWithWordsWrapped = phrase.split(' ').map((word, index) => {
  if (wordsArr.includes(word)) {
    return `<span>${word}</span>`;
  }
  return word;
}).join(' ');

console.log(phraseWithWordsWrapped)

Upvotes: 1

Related Questions