简体   繁体   中英

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM