如何从 javascript 中的字符串数组中删除字符模式?

How to remove a pattern of characters from an array of strings in javascript?

Live code

我有一个字符串数组。每个字符串代表一个路径。我需要删除此路径中语言环境代码之前的所有内容。 我想要return一组新的干净路径。

问题:如何编写和使用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);
    });

最后,我想将原始数组 thingy 过滤为 newThing,输出应如下所示:

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

如果您想转换数组中的项目,filter 不是正确的工具; map 是您使用的工具。

看起来[=44​​=]您只想删除路径的中间部分:

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 将其替换为空白字符串。

如果您想使用捕获组来捕获您想要的片段,您可以做很多相同的事情,只需更改您在 map 回调中所做的事情,然后让它 return 该条目所需的字符串。

作为稍微改变事物的例子,这里有一个类似的东西,它捕获第一个和最后一个片段并在没有中间部分的情况下重新组合它们:

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>

根据需要进行调整。