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

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

本文关键字:删除 字符 模式 数组 字符串 javascript      更新时间:2023-09-26

实时代码

我有一个字符串数组。每个字符串代表一个路径。我需要在此路径中删除区域设置代码之前的所有内容。我想返回一个新的干净路径数组

问题:如何编写和使用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是你使用的工具。

看起来就像你只想去掉路径的中间部分:

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回调中做的事情,并让它返回你想要的字符串。

只是一个稍微改变的例子,这里有一个类似的东西,捕获第一个和最后一个片段并重新组装它们,而不包含中间的部分:

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>