[英]How to remove a pattern of characters from an array of strings in javascript?
I have an array of strings. 我有一个字符串数组。 Each string represents a path. 每个字符串代表一个路径。 I need to remove everything before the locale code in this path. 我需要删除此路径中的语言环境代码之前的所有内容。 I would like this to return a new array of clean paths. 我想返回一个新的干净路径数组。
Question: How to write and use arr.filter()
to match()
then remove all locale's pattern from the original string. 问题:如何编写和使用arr.filter()
进行match()
然后从原始字符串中删除所有语言环境的模式。
Code: 码:
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);
});
In the end, I would like to filter that original array thingy
to newThing
which the output should looks like: 最后,我想筛选原始阵列thingy
到newThing
其应该输出的样子:
console.log(newThing);
// ['home/gosh1.png','about/gosh.png','place/1noway.jpg']
If you want to transform the items in the array, filter
isn't the right tool; 如果要转换数组中的项目,则filter
不是正确的工具; map
is the tool you use. map
是您使用的工具。
It looks like you just want to drop the middle part of the path: 看来您只想删除路径的中间部分:
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>
That uses /\\/[^\\/]+/
, which matches a slash followed by any sequence of non-slashes, and then usese String#replace
to replace that with a blank string. 它使用/\\/[^\\/]+/
,它匹配一个斜杠,后跟任何非斜杠序列,然后使用String#replace
将其替换为空白字符串。
If you wanted to use capture groups instead to capture the segments you wanted, you'd do much the same thing, just change what you do in the map
callback, and have it return the string you want for that entry. 如果您想使用捕获组来捕获所需的段,则可以做很多相同的事情,只需更改您在map
回调中所做的操作,然后让它返回该条目所需的字符串。
Just as an example of changing things slightly, here's a similar thing that captures the first and last segments and reassembles them without the part of the middle: 就像稍微更改内容的示例一样,这是一个类似的内容,它捕获了第一段和最后一段,并在没有中间部分的情况下重新组装了它们:
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>
Tweak as necessary. 根据需要进行调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.