Home > Software design >  How to loop a string an array in string
How to loop a string an array in string

Time:09-17

let names = 'const names = ["jhon", "anna", "kelvin"]'

how to get the names array so i can loop through it

for example names.forEach(name => console.log(name))

// expected results jhon, anna, kelvin

CodePudding user response:

You could use match() here to isolate the array, followed by a split() to obtain a list of names.

var names = 'const names = ["jhon", "anna", "kelvin"]';
var vals = names.match(/\["(.*?)"\]/)[1]
                .split(/",\s*"/)
                .forEach(name => console.log(name));

CodePudding user response:

eval('const names = ["jhon", "anna", "kelvin"]');
for(let name : names)
console.log(name);
  • Related