[英]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.