0

I have a small problem with replace words in html.

<p id ="demo">Hello, Hello how are you! </p>

I want final result like this: Hello, how are you!

It should to filter it to remove duplicate items, join them back.

var span = document.getElementById('demo'),
    text = span.innerHTML.split('').filter(function (allItems,i,p) {
   return i == p.indexOf(allItems);
    }).join('');
    
    span.innerHTML = text;
<p id ="demo">Hello, Hello how are you </p>
Sébastien
  • 11,860
  • 11
  • 58
  • 78
joooo
  • 37
  • 7

2 Answers2

2

This should work:

var span = document.getElementById('demo'),
  text = span.innerHTML.split(/(\W+)/).map(function(currValue, i, array) {
    if (i == array.indexOf(currValue) || i % 2)
      return currValue;
    return '';
  }).join('');

span.innerHTML = text;
<p id="demo">Hello, Hello how are you! </p>

It splits by any sequence of non-word characters and then maps the array and if the item is repeated it returns empty string, else the item. I also save the separators so they can be recovered later - thus the check i % 2 ( if it is a separator always return it - we don't want to filter them).

mdatsev
  • 3,054
  • 13
  • 28
1

You can capture each word, and if the word has not been found yet, add it to a list of unique items. If the word is found, replace it.

function dedupe(string) {
  var unique = [];
  return string
    .replace(/[a-z]+/gi, function(m) {
      if (unique.indexOf(m) < 0) {
        unique.push(m);
        return m;
      }
      return '';
    })
    .replace(/\s+/, ' ');
}

let fixed = dedupe('Hello, Hello how are you!');

console.log(fixed);
KevBot
  • 17,900
  • 5
  • 50
  • 68