filter by part of a path in Node JS

Viewed 62

How I can check if a directory has part of a string like the following :

examples of the directories:

c:\dev\test\modules\frontend-js\packages\federated-search-result-portlet\assets\locales\sv\translation.json

c:\dev\test\modules\frontend-js\packages\federated-search-result-portlet\assets\locales\en\translation.json

c:\dev\test\modules\frontend-js\packages\federated-search-result-portlet\assets\locales\fr\translation.json

path.basename(file) ==='translation.json'  && dir.includes("\\assets\\locales\\en") && !dir.includes("\\assets\\locales\\en_")

so I need to filter more by a specific part of directory :

like I need just when directory has 'assets\locales\en'

It works on Windows, but I want to have it in Linux as well

1 Answers

In the latest NodeJS version you can use those two methods, where the first one uses the includes() method.

const yourString = "c:\dev\test\modules\frontend-js\packages\federated-search-result-portlet\assets\locales\fr\translation.json";

const substring = "assets\locales\fr";

console.log(yourString.includes(substring)); // true
console.log(yourString.indexOf(substring) !== -1); // true

Of course in your example you have to change the string variable to your path.basename(file) values, so they are no static like this and represents a string of the directory path.

To make it work on Windows and Linux at the same time, you can either replace the "/"and "\" by using a regex or replace() method supposing that your path is a normal string that represents the path.

Either way you can also use the find by regex. In the example above, it would be:

yourString.match(regex)

Where your regex could be build up keeping in mind that you will need to replace either "assets\locales\fr" or "assets/locales/fr"

When you use a regular expression, the conventional approach is to use a / character as a delimiter, e.g.:

s/pattern/replacement/g;

But you can use any character instead of a /, for example a pipe:

s|pattern|replacement|g;

Then with that in mind you can build your regex expression. Example: https://regex101.com/r/eQ7aV6/2

Also, keep in mind that you can remove the back/forward slashes and then search for the path without it, like assetslocalesfr or change it with another symbol.

Related