search

Home  >  Q&A  >  body text

How to eliminate specific repeated characters in a string?

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粉354602955P粉354602955227 days ago467

reply all(2)I'll reply

  • P粉416996828

    P粉4169968282024-04-01 09:45:52

    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.

    reply
    0
  • P粉757432491

    P粉7574324912024-04-01 00:37:29

    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);

    reply
    0
  • Cancelreply