1

私は次のようなURLを受け取るjs関数を持っています:

http://example.com/folder1/folder2/../page.html

URLは絶対的ですが../、中央にあるため、それが指す実際のhtmlページは。folder1の代わりに存在することに注意してくださいfolder2

どうすれば変換できhttp://example.com/folder1/folder2/../page.htmlますhttp://example.com/folder1/page.htmlか?

私のURLには複数の部分が含まれている可能性があることに注意してください../

このためのJavascriptの組み込み機能はありますか?(例:C#では、これを実行するURIクラスを介して実行します。)

更新:少し明確にするために、このためにDOM要素を作成または使用したくありません。

4

3 に答える 3

2

function relativeToAbsolute(relativeUrl) {
  var a = document.createElement('a');
  a.href = relativeUrl;
  return a.href;
}

url = relativeToAbsolute("http://example.com/folder1/folder2/../page.html");

console.log(url)

于 2014-05-06T03:08:19.760 に答える
1

これでうまくいくはずです:

function relativeToAbsolute(url){
    arr = url.split("/") // Cut the url up into a array
    while(!!~arr.indexOf("..")){ // If there still is a ".." in the array
        arr.splice(arr.indexOf("..") - 1, 2); // Remove the ".." and the element before it.
    }
    return arr.join("/"); // Rebuild the url and return it.
}
console.log(relativeToAbsolute("http://example.com/folder1/folder2/../page.html"));
console.log(relativeToAbsolute("http://example.com/folder1/folder2/../../page.html"));

// Returns:
// http://example.com/folder1/page.html
// http://example.com/page.html
于 2012-12-05T11:42:07.230 に答える
1

実際にははるかに簡単です。

<a id="mylink" href="/static/img/photo.jpg">My Photo</a>

<script>
var javascript_object = document.getElementById('#mylink');
var url = javascript_object.href; //returns absolute url

//want to write it back? just reverse it
javascript_object.href = url;
</script>

免責事項:私はこれまでChromeでのみテストしました。

于 2012-12-27T23:06:00.873 に答える