I’ve got a simple string with some of the duplicating characters there. Can someone please help me fix the expression below to remove NOT only duplicated characters but ALL characters that have more than 1 occurance.
console.log('aaabbxxstring'.replace(/(.)(?=.*?1)/g,'')); // string
I am capturing a matching character using lookahead and replace the match with a whitespace. The question is how to replace the capturing group itself. Or is the entire approakch incorrect?
3
Answers
Explanation:
I think regex is the wrong tool for this. You need to first count how many times each character occurs in the string before you can decide what characters to remove.
It is probably easier to get it done using a
Map
to keep a count of the characters encountered in the string.Example:
Disclaimer: I’m not used to javascript so there may be more idiomatic ways of doing this .
Count occurrences using the length of the resulting array when you split the string around the chars.
gives you occurrences plus 1.
Convert the string to an array, filter using the occurrences, join to a String.