Esa Kurniawan
Esa Kurniawan

Reputation: 647

How to loop a string an array in string

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

Upvotes: 2

Views: 122

Answers (4)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27222

You 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.

Upvotes: 0

Ghost
Ghost

Reputation: 205

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

Upvotes: 2

BREgitLEEhub2222
BREgitLEEhub2222

Reputation: 41

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

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521997

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));

Upvotes: 4

Related Questions