Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: get words and its indices in a sentence

Tags:

javascript

I need to get all the words from a sentence and also their index position within the sentence. The same word can happen multiple times in the sentence.

I was trying to do this using the filter method but the index indicates the position in the array not the position within the sentence.

var sentence = "This is a short sentence, a demo sentence."

sentence.split(" ").filter((word, index) => {
    
}
like image 518
doorman Avatar asked Oct 28 '25 04:10

doorman


1 Answers

You can use .reduce:

const sentence = "This is a short sentence, a demo sentence.";
let index = 0;
const nonAlphabeticWithoutSpace = /[^a-zA-Z ]/g;

const res = sentence.split(" ").reduce((acc, item) => {
  // get word without other characters
  const word = item.replace(nonAlphabeticWithoutSpace, "");
  // get prev indices of this word
  const wordIndices = acc[word];
  // create/update the indices list
  acc[word] = wordIndices ? [...wordIndices, index] : [index]; 
  // increment the index
  const nonAlphabetic = item.match(nonAlphabeticWithoutSpace);
  index += nonAlphabetic 
    ? word.length+nonAlphabetic.length+1 
    : word.length+1;
  return acc;
}, {});

console.log(res);

If you want to disregard case senstivity, use .toLowerCase().

like image 75
Majed Badawi Avatar answered Oct 30 '25 13:10

Majed Badawi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!