skip to Main Content

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


  1. console.log('aaabbxxstring'.replace(/(.)1+/g, '')); // string
    

    Explanation:

    (.) captures a single character.
    1+ matches one or more occurrences of the captured character.
    /g performs a global search to replace all occurrences.
    
    Login or Signup to reply.
  2. I think 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:

    var str = 'aaabxbxxstringaaa';
    var map = new Map();
    
    // loop over all the characters and count how many times each character occurs
    for(let ch of str) {
      let count = map.get(ch);
      count = count ? count : 0;
      map.set(ch, count + 1);
    }
    
    // remove characters occuring more than once:
    for(let [ch, count] of map) {
      if(count > 1) {
        str = str.replaceAll(ch, '');
      }
    }
    
    console.log(str);

    Disclaimer: I’m not used to javascript so there may be more idiomatic ways of doing this .

    Login or Signup to reply.
  3. Count occurrences using the length of the resulting array when you split the string around the chars.

    str.split(c).length
    

    gives you occurrences plus 1.

    Convert the string to an array, filter using the occurrences, join to a 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search