I just finished my code of the exercise Array 2 and It works fine but I would like to one more thing in it, I would like to add a space between each character name like this: Array: Ryu, Ken, Chun-Li, Cammy, Guile, Sakura, Sagat, Juri
so I created this looping:
for (let i = 0; i < myArray.length; i++) {
let subArray = myArray[i].split(',') + ', '; //here is the place I add the "comma" and "space"
console.log(subArray);
I can access the correct line with console.log but I cannot apply it to the “myArray” variable…
This is my full code:
et myString = 'Ryu+Ken+Chun-Li+Cammy+Guile+Sakura+Sagat+Juri';
let myArray = myString.split('+');
let arrayLength = myArray.length;
for (let i = 0; i < myArray.length; i++) {
et subArray = myArray[i].split(',') + ' ';
console.log(subArray);
}
let lastItem = myArray[7];
It seems to me that if you want to replace all instances of + with , , that you should do this with string methods, before you ever get to splitting the string into an array.
You could use the replace() method to handle this pretty nicely:
let newString = myString.replace(/[+]/g, ', ')
Read more about this on MDN
The /[+]/g bit is a regular expression, and regular expressions are pretty fiddly and hard to work out, but you get used to them with a bit of practice:
/ and / are the boundaries of the regular expression.
+ is the pattern we are trying to search for. I’ve wrapped it in square brackets to make it match for the string literal “+”, otherwise it interprets it as a bit of syntax and you get an error.
The g modifier after the end of the regular expression means “global” — match all the instances of the pattern you find, not just the first one.
You could then go on to split newString into an array if you wanted to, like this:
Thank you for responding that quickly.
Indeed rookie mistake!
Still not working on the console though, but I guess if it’s ok on JSBin, that’s what matters.