Mat*_*ood 2 javascript regex arrays substring filter
我有一个字符串数组。每个字符串代表一条路径。我需要删除该路径中区域设置代码之前的所有内容。我希望它返回一组新的干净路径。
问题: 如何编写和使用从原始字符串中删除所有语言环境的模式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);
});
Run Code Online (Sandbox Code Playgroud)
最后,我想过滤原始数组thingy,newThing输出应如下所示:
console.log(newThing);
// ['home/gosh1.png','about/gosh.png','place/1noway.jpg']
Run Code Online (Sandbox Code Playgroud)
如果你想转换数组中的项目,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));Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)
它使用/\/[^\/]+/,匹配斜杠后跟任何非斜杠序列,然后使用seString#replace将其替换为空白字符串。
如果您想使用捕获组来捕获您想要的段,您将做同样的事情,只需更改您在回调中所做的操作map,并让它返回您想要该条目的字符串。
就像稍微改变一些东西的例子一样,这里有一个类似的东西,它捕获第一个和最后一个片段并重新组装它们,而不需要中间的部分:
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));Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)
根据需要进行调整。