2015-10-05 59 views
2

Live code如何從javascript中的字符串數組中刪除字符模式?

我有一個字符串數組。每個字符串表示一個路徑。我需要刪除此路徑中的區域代碼之前的所有內容。 我想這個返回一個新的乾淨的路徑陣列。

問題:如何編寫和使用arr.filter()match()然後從原始字符串中移除所有區域的模式。

代碼:

var thingy = ['thing/all-br/home/gosh-1.png','thing/ar_all/about/100_gosh.png','thing/br-pt/anything/a_noway.jpg']; 
var reggy = new RegExp('/[a-z]{2}-[a-z]{2}|[a-z]{2}_[a-z]{2}/g'); 


var newThing = thingy.filter(function(item){ 
     return result = item.match(reggy); 
    }); 

最後,我想以過濾原始數組thingynewThing其輸出應該是這樣的:如果你想變換的項目

console.log(newThing); 
// ['home/gosh1.png','about/gosh.png','place/1noway.jpg'] 
+0

只是改變'返回結果= item.match(reggy);'返回'item.match(reggy);' –

+0

仍然不工作:( –

+0

http://jsfiddle.net/arunpjohny/tgL8seyk/1/? - 如果正則表達式是正確的......沒有驗證那部分 –

回答

4

該陣列,filter不是正確的工具; map是您使用的工具。

看起來像你只是要刪除的路徑的中間部分:

var thingy = ['home/all-br/gosh1.png', 'about/ar_all/gosh.png', 'place/br-pt/noway.jpg']; 
 
var newThing = thingy.map(function(entry) { 
 
    return entry.replace(/\/[^\/]+/, ''); 
 
}); 
 
snippet.log(JSON.stringify(newThing));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

使用/\/[^\/]+/,它匹配一個斜線跟着非斜線的任何序列,然後用String#replace替換爲空字符串。

如果您想使用捕獲組來捕獲您想要的段,您可以做同樣的事情,只需更改您在回調中做的操作,並讓它返回該條目所需的字符串。

正如稍微改變事物的一個例子,這裏捕獲的第一和最後一個片段,並重組他們沒有中間的部分類似的事情:

var thingy = ['home/all-br/gosh1.png', 'about/ar_all/gosh.png', 'place/br-pt/noway.jpg']; 
 
var newThing = thingy.map(function(entry) { 
 
    var match = entry.match(/^([^\/]+)\/.*\/([^\/]+)$/); 
 
    return match ? match[1] + "/" + match[2] : entry; 
 
}); 
 
snippet.log(JSON.stringify(newThing));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

調整必要。

+0

對於這種情況'map'確實是正確的/最好的路線 –

+0

@ TJ可以試試var thingy = ['thing/all-br/home/gosh-1.png','thing/ar_all/about/100_gosh.png','thing/br-pt/anything/a_noway.jpg' ];作爲你的凝視陣列 –

+0

因此刪除東西/ / –