2
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

4
  • Why you take the const in the let? This approach is not right. You can take the array in let names. Commented Sep 17, 2022 at 6:22
  • because i take the code from the user input (in my real project) Commented Sep 17, 2022 at 6:37
  • 1
    Whatever you do, avoid the eval and use something like stackoverflow.com/a/73752586/1277159 Commented Sep 17, 2022 at 6:52
  • i take the code from the user input (in my real project). That gives me shivers... Commented Sep 17, 2022 at 9:12

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

that works perfectly for my use cases, but it's using the eval function can you refactor it to not using the eval function?
Ok, I rewrite it using JSON.parse instead of eval. Still work fine.
0
eval('const names = ["jhon", "anna", "kelvin"]');
for(let name : names)
console.log(name);

1 Comment

There are downsides of using eval which you need to highlight to the user and this a code only answer
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.