I will shorten up your code a little bit so it doesn't cause too much confusion to you.
Also, you can avoid the slice method since strings by default are immutable and what that means is that every time you execute the replace method or any other string method it will return a brand new string.
var numbersArray = [1, 2, 3, 5, 6, 3];
var numbersString = numbersArray.join(''); // => '1235653'
var numbersWithoutThrees = numbersString.replace(/3/g, ''); // => '1256'
Great so far! The replace method accepts as an argument a RegExp or a string.
For example: numbersString.replace(/3/g, '');
we're using the /3/g
RegExp that means find all the '3'
occurrences due to the g
flag, since there is a '3'
is going to be replace for the empty string''
defined in the second parameter in the repace
.
But what about the /numbersString[2]/g
? Let's check it out:
var result = numbersString.replace(/numbersString[2]/g, ''); // => '123563'
It seems is not replacing anything and that's because there's no 'numbersString[2]'
string inside '123563'.
If we want to replace the third element (numberSring[2]) you can do it by replacing the element in that position in the numbersArray
and generating a new string by using join once again.
numbersArray[2] = ''; // => [1, 2, "", 5, 6, 3]
numbersString = numbersArray.join(''); // => '12563'
And there it's the result you now don't have that third element on your numbersString
variable.
I hope that helps!