0

I wrote this code to delete certain characters from a string which I convert to an array of characters.

function extractChar(str) {
  var array = [];
  array = str.split('');

  for (i=1;i<arguments.length;i++) {
    for (x=0;x<array.length;x++) {
      if (array[x] === arguments[i]) {
        var temp = array.indexOf(array[x]);
        array.splice(temp,1);
      }
    }
  }
  document.write(array);
}

extractChar('hello my name is frank','f','m','l');

The code works fine for deleting a character that appears once in the array (the 'f' in this case). It also works for deleting double characters that are not adjacent to each other (the 'm's in this case).

However, it does not work for double letters that are adjacent to each other (the 'l's in this case). Why is this? It does work for two different letters that are next to each other (like the 'f' and 'r'). Why not for double letters?

Thank you

2 Answers 2

1

When you splice the array, the next index will decrement by one, so you need to decrement your 'x' accordingly =)

function extractChar(str) { var array = []; array = str.split('');

  for (i=1;i<arguments.length;i++) {
    for (x=0;x<array.length;x++) {
      if (array[x] === arguments[i]) {
        var temp = array.indexOf(array[x]);
        array.splice(temp,1);
        x--;
      }
    }
  }
  document.write(array);
}

extractChar('hello my name is frank','f','m','l');
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly! Thank you :)
0

To delete adjacent double letters in JavaScript, do this

function deleteDuplicates(string) {
    return string.replace(/(.)\1{1,}/g, '');
}

deleteDuplicates("hello")
=> "heo"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.