I'm trying to dynamically create an array from another one in JavaScript. I have a string which is a mathematical literal expression like this '2a + 3b + 4a + 5c': I just want to split it into an array with only the literal part of the number (Ex. 'a,b,a,c').
I've tried to use the following code to do this :
var expression = '2a + 3b + 4a + 5c';
var NumbersArray = expression.split(' + '); /* NumbersArray = 2a,3b,4a,5c */
alert('So far it's working!');
var LettersArray = new Array();
for (var i = 0; i < NumbersArray.length; i++) {
eval('var LettersArray[' + i + '] = NumbersArray[' + i + '].replace(/[0-9]/g,"");');
alert(eval('LettersArray[' + i + ']'));
}
But it doesn't work! How can I fix it?
alert, the apostrophe needs to be escaped.it'sis ending the string). Also, why are you using eval?