42

URL の最後のディレクトリ部分を削除しようとしています。私の URL は次のようになります。

https://my_ip_address:port/site.php?path=/path/to/my/folder.

ボタンをクリックすると、これを次のように変更したい

https://my_ip_address:port/site.php?path=/path/to/my. (最後の部分を削除します)。

私はすでに試しましたがwindow.location.replace(/\/[A-Za-z0-9%]+$/, "")、その結果

https://my_ip_address:port/undefined.

これを行うにはどの正規表現を使用すればよいですか?

4

5 に答える 5

47

Explanation: Explode by "/", remove the last element with pop, join again with "/".

function RemoveLastDirectoryPartOf(the_url)
{
    var the_arr = the_url.split('/');
    the_arr.pop();
    return( the_arr.join('/') );
}

see fiddle http://jsfiddle.net/GWr7U/

于 2013-05-25T14:50:23.433 に答える
3

ディレクトリ パスの末尾を削除する別の方法:

path.normalize(path.join(thePath, '..'));
于 2020-11-11T10:43:08.257 に答える
0

ネイティブ ライブラリに固執すると、dirname役立つ場合があります。


(nodeバックエンド)

const path = require('path')
let str='https://my_ip_address:port/site.php?path=/path/to/my/folder'
console.log(path.dirname(n))
console.log(path.dirname(n)+'/')

出力は

'https://my_ip_address:port/site.php?path=/path/to/my'
'https://my_ip_address:port/site.php?path=/path/to/my'

Firefox ブラウザー ( MDN、Path Manuplation、OS.Path.dirnameを参照)

let str='https://my_ip_address:port/site.php?path=/path/to/my/folder'
console.log(OS.path.dirname(n))
console.log(OS.path.dirname(n)+'/')


申し訳ありませんが、Chromium については何も見つかりませんでした。

于 2020-10-25T21:17:04.320 に答える