-2
var nums = [1,2,3,5,6,3];
nums = nums.join('')
// I want to replace all occurrences of 3 in nums with an empty string.

// this code works
nums.slice(0).replace(/3/g,''); => [1,2,5,6];

// this code doesn't work, because I replaced 3 with a variable
nums.slice(0).replace(/nums[2]/g, ''); => [1,2,3,5,6,3]; 

whenever I use an actual character, it works but when I replace it with a variable like (nums[2]), it doesn't work and just returns the same array. is there something I'm missing?

  • 1
    The regex literal syntax does not interpolate the values of variables; it's like a string literal (not a string template). The regex `/nums[2]/` means to match the characters "n u m s 2". – Pointy Apr 08 '20 at 17:11
  • 3
    Does this answer your question? [How do you use a variable in a regular expression?](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression) – ASDFGerte Apr 08 '20 at 17:11
  • 2
    …though in fact you should not use regex at all here. Do not convert the array to a string. Use `filter` to omit values from your array. – Bergi Apr 08 '20 at 17:15

1 Answers1

0

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!

lndgalante
  • 402
  • 2
  • 4