0

I have seen a few examples of this, but they're either not in JS or are terribly inefficient (like the solution I have now). Basically what I want done is a function that takes in a string and removes any characters that are adjacent and the same. As an example, "jjjavvvaaassscript" would become "javascript". What I'm not looking for is where it would become "javscript" (eliminating the second "a"). I do have a working function shown below, but it's absolutely horrendous and I'm looking for a better way to do it.

function removeChar(text, index) {
    return(text.slice(0,index)+text.slice(index+1));
}

function removeDuplicates(text) {
    var prevChar = "";
    var finalT = text;
    var i = 0;
    for(i = 0; i < text.length; i++) {
        if(finalT.charAt(i) == prevChar) {
            if(i > finalT.length) {
                return finalT;
            } else {
                finalT = removeChar(finalT, i);
                i--;
            }
        } else {
            prevChar = finalT.charAt(i);
        }
    }
    return finalT;
}

Any help would be greatly appreciated!

0

1 Answer 1

1

I'd use a regular expression to match a character, then backreference it as many times as possible (so, for example, it'll match jjj, or a, or vvv, etc), and then replace with the one character:

const removeDuplicates = str => str.replace(/(.)\1*/g, '$1');
console.log(removeDuplicates('jjjavvvaaassscript'));

If you had to iterate more manually, similar to your current method, then:

const removeDuplicates = str => {
  let lastChar = str[0];
  let finalT = str[0];
  for (const char of str.slice(1)) {
    if (lastChar !== char) finalT += char;
    lastChar = char;
  }
  return finalT;
};
console.log(removeDuplicates('jjjavvvaaassscript'));

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe \1+ would be better, since you don't need to replace a character that has no duplicates

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.