How to eliminate specific repeated characters in a string?
P粉354602955
P粉354602955 2024-03-31 10:50:33
0
2
516

I have a simple string with some repeating characters. Can someone please help me fix the expression below to remove not only duplicate characters but all characters that occur more than 1 time.

console.log('aaabbxxstring'.replace(/(.)(?=.*?)/g,'')); // string

I am using lookahead to capture matching characters and replace the match with spaces. The question is how to replace the capturing group itself. Or is the entire approach incorrect?

P粉354602955
P粉354602955

reply all(2)
P粉416996828
console.log('aaabbxxstring'.replace(/(.)+/g, '')); // string

illustrate:

(.) captures a single character.
+ matches one or more occurrences of the captured character.
/g performs a global search to replace all occurrences.
P粉757432491

When you split a string around characters, use the length of the resulting array to count occurrences.

str.split(c).length

Provides you with the number of occurrences plus 1.

Convert the string to an array, filter by the number of occurrences, and connect to the string.

var str = 'aaabxbxxstring';

const count = (str, c) => str.split(c).length - 1

str = [...str].filter(c => count(str,c) < 2).join('')

console.log(str);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template