Home > Enterprise >  Remove duplicate words except numbers
Remove duplicate words except numbers

Time:02-24

I need to remove duplicate words in a string, but not the numeric characters.

Here's an example of text that I need to convert and keep the numeric characters. Any suggestions on how to handle this?

String example: "Rim - Rim Black 28H 700mm x 700mm"

  static removeDuplicateWords = (statement: string) => {
    return statement
      .split(" ")
      .filter((item, pos, self) => {
        return self.indexOf(item) === pos;
      })
      .join(" ");
  };

Current Results: - Rim Black 28H x 700mm

Expected results: - Rim Black 28H 700mm x 700mm

Thanks for the help

CodePudding user response:

Use a regular expression to test if the word contains a digit.

static removeDuplicateWords = (statement: string) => {
  return statement
    .split(" ")
    .filter((item, pos, self) => item.match(/\d/) || self.indexOf(item) === pos)
    .join(" ");
};

CodePudding user response:

From your example, you can create a set of the split string and join it again.

console.log(Array.from(new Set("Rim - Rim Black 28H 700mm x 700mm".split(' '))).join(' '))

// print 'Rim - Black 28H x 700mm'

  • Related