LoginSignup
2
0

More than 1 year has passed since last update.

【JS】相対パスを正規表現でディレクトリ部分とファイル名部分に分ける

Last updated at Posted at 2021-10-14

正規表現を使ってディレクトリとファイル名に分ける

おれおれ、かんたん忘備録。

基本

script.js
const path = '/acchi/kocchi/socchi/test.html';
const dir = path.replace(/[^/]*$/, ''); // '/acchi/kocchi/socchi/'
const file = path.replace(/.*\//, ''); // 'test.html'

replace(/[^/]*$/, '')replace(/.*\//, '') が味噌です。

応用

ある特定のディレクトリ内の*test.htmlを全てignoreしたい!ってときに、
ファイルを比較するのに使える。使った。もっといい書き方、あるかも。

対象:
- /acchi/kocchi/socchi/*test.html
- /acchi/kocchi/socchi/test.html

script.js
const targetPathList = [
    '/acchi/kocchi/socchi/test.html',
    '/acchi/kocchi/socchi/_test.html',
    '/acchi/kocchi/socchi/OLDtest.html',
];
const ignorePathList = [
    '/acchi/kocchi/socchi/test.html',
    '/acchi/socchi/test.html', // 増やしていってもok
];

for (let i = 0; i < targetPathList.length; i++) {
    const target_dir = targetPathList[i].replace(/[^/]*$/, '');
    const target_file = targetPathList[i].replace(/.*\//, '');
    let flag = false;

    for (let j = 0; j < ignorePathList.length; j++) {
        const ignore_dir = ignorePathList[j].replace(/[^/]*$/, '');
        const ignore_file = ignorePathList[j].replace(/.*\//, '');
        const file_regex = new RegExp(ignore_file + '$'); // = test.html$

        const dir_check = (ignore_dir == target_dir);
        const file_check = target_file.match(file_regex);

        if(dir_check && file_check) {
            flag =  true;
            break;
        }
    }

    if(flag) {
        console.log(targetPathList[i] + 'は、ignore対象ファイルです。');
        // ~~~~~ 以下に任意の記述 ~~~~~
    }
}


背景

バックエンドPythonとフロントエンドJSを使って、JSベースの自作FTPソフトを作っているときに
FTP対象外ファイルを特定の条件ではじきたかったので上記に至った。

2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0