2015-10-05 53 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

因此删除东西/ / –