9

ユーザーをさまざまな URL から特定の URL にリダイレクトしたいと考えています。さまざまな種類の置換を試しましたが、必要な動作が得られないようです。このコードは、ホスト名を指定する以外は機能します。windows.location.hostname の既存のホスト名を使用して、新しいパス名を指定したいだけです。URL のサイズやスラッシュ (「/」) が異なる場合があります。

window.location = 'http://localhost:36065/NewPath';

これらの URL を変更するにはどうすればよいですか?

http://somesite.com/xxx/yyy/zzz to http://somesite.com/NewPath
http://somesite.com/xxx/yyy to http://somesite.com/NewPath
http://somesite.com/xxx to http://somesite.com/NewPath

私はあなたがポイントを得ると思います。パスはパスによって異なる場合があります。基本的に .com の後のすべてを「NewPath」に置き換えたい

可能であればクリーンな正規表現ソリューションが欲しいのですが、私はその部門の新人です。ヒントやコツをありがとう。

4

3 に答える 3

25
location.pathname = '/newpath.html'
于 2011-10-13T16:35:30.703 に答える
4

さまざまなlocationプロパティをいつでも使用して、必要な部分を再作成し、新しい部分をそれに追加できます。

window.location = location.protocol + "//" + location.hostname + "/NewPath";
于 2011-10-13T16:35:01.633 に答える
0

難しい方法を示すために:

// Find everything up to the first slash and save it in a backreference
regexp = /(\w+:\/\/[^\/]+)\/.*/;

// Replace the href with the backreference and the new uri
newurl = windows.location.href.replace(regexp, "$1/dir/foo/bar/newpage.html");
于 2011-10-13T17:06:48.543 に答える