22

リンクから URI エンコーディングを削除しようとしていますが、decodeURI が完全に機能していないようです。

私のリンク例は次のとおりです。/linkout?remoteUrl=http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-heroic-armies-marching

JavaScript スクリプトを実行すると、次のようになります。

http%3a%2f%2fsandbox.yoyogames.com%2fgames%2f171985-h-a-m-heroic-armies-marching

URI に残っている正しくないコードを取り除くにはどうすればよいですか?

私のデコードコード:

var href = $(this).attr('href');            // get the href
var href = decodeURI(href.substring(19));   // remove the outgoing part and remove the escaping
$(this).attr('href', 'http://'+href)        // change link on page
4

3 に答える 3

53

URL は 2 回エンコードされたように見えます。また、decodeURIComponent を使用することをお勧めします

decodeURIComponent(decodeURIComponent("http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-heroic-armies-marching"))

結果: "http://sandbox.yoyogames.com/games/171985-ham-heroic-armies-marching"

ただし、URLを2回エンコードした理由を事前に確認する必要があります

于 2012-07-04T06:40:50.807 に答える
1

PUT動詞のASHXハンドラーでこの状況に遭遇しました。ASP.NET が私の XML をエンコードしているように見えるので、サーバー側でHttpUtility.UrlEncodeを呼び出す必要はありませんでした。クライアント側の Javascript のdecodeURIを 2 回呼び出して修正すると、牛がすでに去った後に納屋のドアが閉まり、送信していた HTTP がプロトコル違反でした。

Tobias Krogh の回答にコメントしてプラス 1 したかったのですが、そうするポイントがありません…</p>

ただし、ここで説明されている失敗は Javascript の decodeURI などではなく、データ検証エラーであることに注意することが重要だと思います。

于 2014-06-13T16:54:34.097 に答える
1

私の実装は再帰関数です:

export function tryDecodeURLComponent(str: string, maxInterations = 30, iterations = 0): string {
    if (iterations >= maxInterations) {
        return str;
    } else if (typeof str === 'string' && (str.indexOf('%3D') !== -1 || str.indexOf('%25') !== -1)) {
        return tryDecodeURLComponent(decodeURIComponent(str), maxInterations, iterations + 1)
    }

    return decodeURIComponent(str);
}
  • str: エンコードされた文字列。
  • maxInterations: デコードを試行する再帰的反復の最大回数str(デフォルト:30 )。
  • iterations: フラグ カウンター反復。
于 2020-07-31T00:43:55.430 に答える