简体   繁体   English

如何在字符串中循环字符串数组

[英]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))例如 names.forEach(name => console.log(name))

// expected results jhon, anna, kelvin // 预期结果 jhon, anna, kelvin

You could use match() here to isolate the array, followed by a split() to obtain a list of names.您可以在此处使用match()来隔离数组,然后使用split()来获取名称列表。

 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.您可以在String.match()方法的帮助下使用RegEx来简单地实现这一点。

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. \[.*\] - 包括开/关括号以及内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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