const 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
const 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
You can try this one:
let testCase1 = 'const names = ["jhon", "anna", "kelvin"]';
let testCase2 = 'var names = ["cane", "anna", "abel", 1, {}, []]';
let testCase3 = 'var names = ["cane" "anna", "abel", 1, {}, []]';
function getArrayLikeInsideText(text) {
const regex = new RegExp(/\[.*\]/, 'g');
const temp = text.match(regex);
let arr;
try {
arr = JSON.parse(temp);
} catch {
return undefined;
}
const gotAnArray = Array.isArray(arr);
return gotAnArray ? arr : undefined;
}
console.log(getArrayLikeInsideText(testCase1)); // ["jhon", "anna", "kelvin"]
console.log(getArrayLikeInsideText(testCase2)); // ["cane", "anna", "abel", 1, {}, []]
console.log(getArrayLikeInsideText(testCase3)); // undefined
eval('const names = ["jhon", "anna", "kelvin"]');
for(let name : names)
console.log(name);
eval which you need to highlight to the user and this a code only answerYou can simply achieve this by using a RegEx with the help of String.match() method.
Live Demo :
const names = 'const names = ["jhon", "anna", "kelvin"]';
const a = names.match(/\[.*\]/g)[0];
JSON.parse(a).forEach(name => console.log(name));
\[.*\] - Including open/close brackets along with the content.