-2

I have a sentence and an array of texts.

sentence = 'Hi I am fine. how are you'
arrayOfTexts = ['Hi','I am','how','how are','how are you']
replacedText = '** * ** fine. *** *** ***'

So what I want to do here, I want to compare the sentence words that are matched with an array of text values and replace them with stars ' * '.

Conditions:

  1. The first preference to replace the words is higher when multiple words are matching rather than single. Exp:how are you to replace with how are you not how nor how are. You can think as higher grams replace first.
  2. Currently, I only want up to 4 grams (4 pairs).

My solution I am converting my sentence up to 4 grams and search every pair one by one but I think its a little bit redundant.

sentenceArray = ['Hi I am fine', 'I am fine .', 'am fine . how', 'fine . how are', '. how are you','Hi I am', 'I am fine', 'am fine .', 'fine . how', '. how are', 'how are you','Hi I', 'I am', 'am fine', 'fine .', '. how', 'how are', 'are you','Hi', 'I', 'am', 'fine', '.', 'how', 'are', 'you']

My Question Is there any better way to solve this problem?

Himanshu Teotia
  • 1,435
  • 19
  • 31

1 Answers1

1

You can sort the arrayOfTexts by string length (put the longest first), then turn it into a regular expression that alternates between each possible string, and perform a global replacement:

const sentence = 'Hi I am fine. how are you';
const arrayOfTexts = ['Hi','I am','how','how are','how are you']
  .sort((a, b) => b.length - a.length);
const pattern = new RegExp(arrayOfTexts.join('|'), 'g');

console.log(sentence.replace(pattern, 'FOO'));

For more dynamic replacement, you can pass a callback to .replace instead, or use $& in the replacement string to be substituted with the matched substring there.

If the arrayOfTexts may contain characters with a special meaning in a regular expression, pass them through an escaper function before passing to new RegExp.

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
  • @aravind The sorting is only needed to ensure the order of phrases that start with the same character, eg `how` vs `how are`. If the phrases do not start with the same words, then it doesn't matter in which relative order they're in in the pattern, so sorting by length works. – CertainPerformance May 07 '20 at 12:46
  • Can you also tell me how I can replace the words with stars exactly the same format? – Himanshu Teotia May 07 '20 at 14:49
  • Like I said in the answer, *For more dynamic replacement, you can pass a callback to .replace instead* - the replacer function takes as an argument the matched substring, so you can take its length and repeat `*` that many times with `String.prototype.repeat` – CertainPerformance May 07 '20 at 14:51