Search code examples
javascriptarraysreactjsstring

How to remove only one of repeated chars in string using JavaScript


I have a string with repeated chars like : 'CANADA'.
And I am trying to get the string which removed only one of repeated chars :
'CNADA', 'CANDA', 'CANAD'.

I've tried it with subString, but it returned the part of string removed. Also I've tried it with reduce, but it ended up removing all the repeated chars ('CND').

What is the way of removing only one char at time? The results can be stored in array. (results = ['CNADA', 'CANDA', 'CANAD'])

Thank you.


Solution

  • You can achieve this by utilizing the second parameter of String#indexOf() which specifies the position from which to start the search. Here in a while loop, and using a Set to remove dulplicates before returning.

    function getReplaceOptions(str, char) {
      let res = [], i = str.indexOf(char, 0);
      while (i !== -1) {
        res.push(str.substring(0, i) + str.substring(++i));
        i = str.indexOf(char, i)
      }
      return Array.from(new Set(res))
    }
    
    console.log(getReplaceOptions('CANADA', 'A'));
    console.log(getReplaceOptions('Mississippi', 's'));