0

I am having problem finding the proper method to accomplish this in JS. I want to iterate through each character of string (assume all lower cased) while removing ith character only.

So if I have string abc, I will iterate it three times and it will print:

'bc' //0th element is removed
'ac' //1st element is removed
'ab' //2nd element is removed

I thought I could do it with replace, but it did not work on string having multiple same characters.

Something like this:

str = 'batman';

for(var i = 0; i < str.length; i++){
  var minusOneStr = str.replace(str[i], '');
  console.log(minusOneStr);
}

"atman"
"btman"
"baman"
"batan"
"btman" //need it to be batmn
"batma" 

I realized this didn't work because str.replace(str[i], ''); when str[i] is a, it will replace the first instance of a. It will never replace the second a in batman. I checked on substring, splice, slice method, but none suits mf purpose.

How can I accomplish this?

Iggy
  • 5,129
  • 12
  • 53
  • 87

1 Answers1

6

Instead of using .replace() you'd just concatenate slices of the string before and after the current index.

var str = 'batman';

for (var i = 0; i < str.length; i++) {
  var minusOneStr = str.slice(0, i) + str.slice(i + 1);
  console.log(minusOneStr);
}

This is because, as you noted, .replace(), when given a string, always replace the first instance found.