[英]Replace string in array loop
遍历字符串数组并使用正则表达式替换值的最佳方法是什么? 数组看起来像这样:
['./content1/App.js', './sample2/App.js', './exam/App.js']
我需要生成具有值的新数组:
['content1', 'sample2', 'exam']
您可以在这里使用正则表达式/(?<=\.\/)[^\/]+/
const arr = ["./content1/App.js", "./sample2/App.js", "./exam/App.js"]; const result = arr.map((s) => s.match(/(?<=\.\/)[^\/]+/)[0]); console.log(result);
如果数据项模式相同,那么您可以尝试:
var data = ['./content1/App.js', './sample2/App.js', './exam/App.js']; var res = data.map(i => i.split('/')[1]); console.log(res);
使用阵列原型的 map 方法可以实现这一点。
let newArray =['./content1/App.js', './sample2/App.js', './exam/App.js'].map((string)=>{ // code to replace string //return the modified string })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.