Skip to content

Instantly share code, notes, and snippets.

@RhinoLu
Last active November 30, 2017 07:18
Show Gist options
  • Save RhinoLu/7843c87340800212bb06df0e458bb0ac to your computer and use it in GitHub Desktop.
Save RhinoLu/7843c87340800212bb06df0e458bb0ac to your computer and use it in GitHub Desktop.
redirect desktop to mobile, mobile to desktop 轉址,手機桌機互轉
// 手機轉桌機
const href1 = "https://www.example.com/m/index.html?utm_source=fb&utm_medium=linked#home";
$("#p1-before").text(href1);
// 以陣列處理
const arr1 = href1.split("/");
const index1 = arr1.indexOf("m");
arr1.splice(index1, 1);
$("#p1-after-1").text(arr1.join("/"));
// 正則 比較簡短 shorter!
const after1 = href1.replace(/\/m\//, "/"); // 將 /m/ 取代成 /
$("#p1-after-2").text(after1);
// 桌機轉手機
const href2 = "https://www.example.com/index.html?utm_source=fb&utm_medium=linked#home";
$("#p2-before").text(href2);
// 以陣列處理
const arr2 = href2.split("/");
arr2.splice(-1, 0, "m");
$("#p2-after-1").text(arr2.join("/"));
// location 重組,但前提是 pathname 不能包含 xxx.html
// 若 pathname 包含 xxx.html,還是要用陣列法
// location 在 codepen 不能用喔
// const after2 = location.protocol + "//" + location.host + location.pathname + "m/" + location.search + location.hash;
// $("#p2-after-2").text(after2);
<p>Mobile to Desktop ( remove m )</p>
<p id="p1-before"></p>
<p id="p1-after-1"></p>
<p id="p1-after-2"></p>
<br>
<p>Desktop to Mobile ( add m )</p>
<p id="p2-before"></p>
<p id="p2-after-1"></p>
<p id="p2-after-2"></p>
@RhinoLu
Copy link
Author

RhinoLu commented Nov 30, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment