[FIXED] How to loop a string an array in string

Issue

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


Solution

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



Answered By - Ghost
Answer Checked By - Terry (Python.Easybugfix Volunteer)

Related Posts

Post a Comment