DEV Community

Cover image for Clean Up Messy Facebook, Instagram, TikTok and YouTube Links in JavaScript Before They Break Your Order Form
SEO - NT Tech Innovation
SEO - NT Tech Innovation

Posted on

Clean Up Messy Facebook, Instagram, TikTok and YouTube Links in JavaScript Before They Break Your Order Form

By MD Fozla Rabbi, SEO Specialist

Here's a fun fact about Filipino Facebook users. Nobody, and I mean nobody, pastes a clean link.

You get m.facebook.com links. You get fb.watch short links. You get links with ?mibextid= and fifteen tracking parameters glued on. Sometimes you get a screenshot of the link. (Can't help you there.)

If you run any kind of order form for social media services, messy links are your biggest silent problem. Orders sit stuck. Customers get annoyed. Someone spends their evening fixing URLs by hand.

So let's fix it in code. This post walks through a small JavaScript URL normalizer that cleans and classifies Facebook, Instagram, TikTok and YouTube links before they ever hit your database. No libraries. Works in the browser and in Node.

Why this matters more than you'd think

A friend runs a small reselling page in Davao. She showed me her support inbox. I counted. Roughly a third of her "my order isn't moving" messages came down to one thing: the link was wrong.

Wrong how?

  • A profile link sent for a likes order (likes need a post link)
  • A post link sent for a followers order
  • A private Instagram account
  • A mobile or share link the provider couldn't read
  • A link with a typo, like instagarm.com (yes, really)

Most of these can be caught in about 80 lines of JavaScript. Let's build it.

Step 1: Parse safely

Never regex a whole URL from scratch. Use the built-in URL class. It handles the weird edge cases for you.

function parseLink(raw) {
  let s = (raw || "").trim();
  if (!s) return null;
  if (!/^https?:\/\//i.test(s)) s = "https://" + s; // people skip the protocol
  try {
    return new URL(s);
  } catch {
    return null;
  }
}
Enter fullscreen mode Exit fullscreen mode

That https:// fix alone catches a surprising number of "invalid link" errors. People type instagram.com/shopname all the time.

Step 2: Normalize the host

Lots of hosts point to the same platform. Collapse them.

const HOST_MAP = {
  "facebook.com": "facebook", "m.facebook.com": "facebook",
  "web.facebook.com": "facebook", "mbasic.facebook.com": "facebook",
  "fb.com": "facebook", "fb.watch": "facebook",
  "instagram.com": "instagram", "instagr.am": "instagram",
  "tiktok.com": "tiktok", "vm.tiktok.com": "tiktok", "vt.tiktok.com": "tiktok",
  "youtube.com": "youtube", "m.youtube.com": "youtube", "youtu.be": "youtube",
};

function platformOf(url) {
  const host = url.hostname.toLowerCase().replace(/^www\./, "");
  return HOST_MAP[host] || null;
}
Enter fullscreen mode Exit fullscreen mode

Notice web.facebook.com. That one shows up a lot in the Philippines because of how some free-data promos route Facebook. Little local detail. Easy to miss if you only test with your own browser.

Step 3: Strip the junk

Tracking params make links long and sometimes break provider parsers. Drop them. But be careful: some params are the content. YouTube's v is the video ID. Facebook's story_fbid and id identify a post.

const KEEP = {
  youtube: ["v"],
  facebook: ["story_fbid", "id", "v", "fbid"],
  instagram: [],
  tiktok: [],
};

function cleanParams(url, platform) {
  const keep = new Set(KEEP[platform] || []);
  for (const key of [...url.searchParams.keys()]) {
    if (!keep.has(key)) url.searchParams.delete(key);
  }
  url.hash = "";
  return url;
}
Enter fullscreen mode Exit fullscreen mode

Whitelist, not blacklist. New tracking params appear every few months. A whitelist doesn't care.

Step 4: Classify the link type

This is the part that actually saves support tickets. Is it a profile, a post, a reel or a video?

function linkType(url, platform) {
  const p = url.pathname.replace(/\/+$/, "");
  switch (platform) {
    case "instagram":
      if (/^\/(p|reel|tv)\/[\w-]+/.test(p)) return "post";
      if (/^\/stories\//.test(p)) return "story";
      if (/^\/[\w.]+$/.test(p)) return "profile";
      break;
    case "tiktok":
      if (/\/video\/\d+/.test(p)) return "post";
      if (/^\/@[\w.]+$/.test(p)) return "profile";
      if (url.hostname.startsWith("v")) return "short"; // vm./vt. needs resolving
      break;
    case "youtube":
      if (url.hostname === "youtu.be" || url.searchParams.get("v")) return "post";
      if (/^\/shorts\//.test(p)) return "post";
      if (/^\/(@|channel\/|c\/)/.test(p)) return "profile";
      break;
    case "facebook":
      if (url.hostname === "fb.watch") return "short";
      if (/\/(posts|videos|reel|photo|watch)/.test(p) || url.searchParams.get("story_fbid")) return "post";
      if (/^\/[\w.]+$/.test(p) || /profile\.php/.test(p)) return "profile";
      break;
  }
  return "unknown";
}
Enter fullscreen mode Exit fullscreen mode

Is it perfect? No. Facebook URLs are a beautiful chaos. But it handles the common 90%. The rest get flagged as unknown and a human looks at them. That's fine.

Step 5: Put it together with a clear error message

The function returns either a clean result or a friendly reason. Friendly matters. "Invalid input" helps no one.

function checkLink(raw, expected /* "post" | "profile" */) {
  const url = parseLink(raw);
  if (!url) return { ok: false, msg: "That doesn't look like a link. Try copying it again." };

  const platform = platformOf(url);
  if (!platform) return { ok: false, msg: "We only support Facebook, Instagram, TikTok and YouTube links." };

  cleanParams(url, platform);
  const type = linkType(url, platform);

  if (type === "short") return { ok: true, platform, type, url: url.href, resolve: true };
  if (expected && type !== expected && type !== "unknown") {
    const need = expected === "post" ? "a post or video link" : "your profile or page link";
    return { ok: false, msg: `This looks like a ${type} link. For this service we need ${need}.` };
  }
  return { ok: true, platform, type, url: url.href };
}
Enter fullscreen mode Exit fullscreen mode

Quick test:

checkLink("m.facebook.com/someshop/posts/123?mibextid=abc", "post");
// { ok: true, platform: "facebook", type: "post",
//   url: "https://m.facebook.com/someshop/posts/123" }

checkLink("instagram.com/milkteaph", "post");
// { ok: false, msg: "This looks like a profile link. For this service we need a post or video link." }
Enter fullscreen mode Exit fullscreen mode

That second message alone could cut a big slice of tickets.

Step 6: Resolve short links on the server

fb.watch, vm.tiktok.com and vt.tiktok.com are redirects. You can't classify them until you follow them. Do it server-side with a HEAD request and a short timeout.

async function resolveShort(href) {
  const res = await fetch(href, {
    method: "HEAD",
    redirect: "follow",
    signal: AbortSignal.timeout(8000),
  });
  return res.url; // final destination
}
Enter fullscreen mode Exit fullscreen mode

Then run the result through checkLink again. Cache the resolution for a day. Same links get pasted over and over.

Where this fits in a real order flow

If you're a reseller pulling services from an SMM panel Philippines users rely on, the panel needs a correct link to start the order. It can't guess what you meant. So the normalizer sits right at the front:

  • Customer pastes link
  • checkLink() runs in the browser for instant feedback
  • Server runs it again (never trust only the client) and resolves short links
  • Clean URL goes into your order record
  • Only then does the order go to the provider's API

Each service on a catalog like BoostingPH's service list says whether it wants a post link or a profile link. Store that as expected on your own service table. Then the check is automatic.

A few edge cases I hit

Honestly, this list keeps growing:

  • Facebook Pages with numeric IDs like profile.php?id=1000... — keep the id param or you lose the page.
  • Instagram usernames with dots — \w doesn't match . so add it explicitly.
  • YouTube Shorts — treat as a video post, not a separate type, unless your services split them.
  • Uppercase hosts — Instagram.com from phone autocorrect. Lowercase the hostname first.
  • Emoji or spaces pasted with the link — trim() plus URL handles most of it.
  • Private accounts — you can't detect these from the URL. Ask the customer to confirm the account is public with a checkbox.

Testing it properly

Keep a file of real, ugly links customers actually sent (with personal info removed). Run every one through the function on each change. Mine has about 120 lines now. It caught two regressions last month that I would have shipped otherwise.

import assert from "node:assert";
import cases from "./link-cases.json" with { type: "json" };

for (const c of cases) {
  const r = checkLink(c.input, c.expected);
  assert.equal(r.ok, c.ok, c.input);
}
console.log("all good");
Enter fullscreen mode Exit fullscreen mode

Boring tests. Big payoff.

Wrapping up

Clean input is the cheapest reliability upgrade you can make. Before you build fancy dashboards or bots, fix the links. Your support inbox will thank you. So will your customers, who mostly just want to know their order is moving.

If you're wiring this into an actual provider integration, the API docs are at https://boostingph.com/api so you can see which link format each action expects.

Got a cursed Facebook URL that breaks this? Paste it in the comments. I collect them.

Top comments (0)