To check if the current browser URL contains a specific substring in JavaScript, validate that window / window.location is available and that the target substring is a non-empty string, read window.location.href (or target a specific URL part such as pathname, search, or hash when avoiding false matches in query parameters or fragments), and perform the check with .includes() inside a try / catch block.
1. Checking the Full URL (window.location.href) Safely
Validate the environment and target substring before calling .includes() on window.location.href, with optional case-insensitive matching:
// Check whether the current browser URL contains a given substring
function urlContainsSubstring(substring, { caseSensitive = true, targetLocation = null } = {}) {
if (typeof substring !== "string" || substring.length === 0) {
throw new TypeError("Expected substring to be a non-empty string.");
}
if (typeof caseSensitive !== "boolean") {
throw new TypeError("Expected caseSensitive to be a boolean.");
}
const activeLocation = targetLocation ?? (typeof window !== "undefined" ? window.location : null);
if (!activeLocation || typeof activeLocation.href !== "string") {
throw new Error("Browser location object with a valid href string is unavailable.");
}
try {
const currentUrl = activeLocation.href;
if (caseSensitive) {
return currentUrl.includes(substring);
}
return currentUrl.toLowerCase().includes(substring.toLowerCase());
} catch (error) {
throw new Error(`Failed checking URL for substring "${substring}": ${error.message}`);
}
}
// Example usage:
// try {
// const isCheckout = urlContainsSubstring("/checkout", { caseSensitive: false });
// console.log("Contains /checkout:", isCheckout);
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
- Guard
windowandwindow.location.href: Prevents runtime errors in non-browser or restricted iframe environments. - Pass a non-empty
substring: Calling.includes("")returnstruefor every string, which usually masks missing input bugs.
2. Inspecting Specific URL Segments with a Map (pathname, search, hash)
Checking window.location.href matches across the entire URL—including domain names, query strings, and hash fragments. Store normalized URL parts in a Map when you need targeted checks across specific segments:
// Inspect specific parts of a Location-like object using a Map
function getUrlSegmentsMap(locationObj = (typeof window !== "undefined" ? window.location : null)) {
if (!locationObj || typeof locationObj.href !== "string") {
throw new Error("Expected a valid location object with an href string.");
}
try {
const parsedUrl = new URL(locationObj.href);
return new Map([
["href", parsedUrl.href],
["origin", parsedUrl.origin],
["pathname", parsedUrl.pathname],
["search", parsedUrl.search],
["hash", parsedUrl.hash]
]);
} catch (error) {
throw new Error(`Failed parsing URL segments: ${error.message}`);
}
}
function segmentContainsSubstring(segmentKey, substring, locationObj = null) {
if (typeof segmentKey !== "string" || segmentKey.trim().length === 0) {
throw new TypeError("Expected segmentKey to be a non-empty string.");
}
if (typeof substring !== "string" || substring.length === 0) {
throw new TypeError("Expected substring to be a non-empty string.");
}
try {
const segmentsMap = getUrlSegmentsMap(locationObj);
if (!segmentsMap.has(segmentKey)) {
throw new RangeError(`Unknown URL segment key "${segmentKey}".`);
}
const segmentValue = segmentsMap.get(segmentKey);
return typeof segmentValue === "string" && segmentValue.includes(substring);
} catch (error) {
throw new Error(`Failed checking URL segment "${segmentKey}": ${error.message}`);
}
}
// Example usage:
// try {
// const hasTabParam = segmentContainsSubstring("search", "tab=security");
// console.log("Query has tab=security:", hasTabParam);
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
- Use
pathnameinstead ofhrefwhen checking routes: Prevents query parameters or redirect URLs like?next=/adminfrom matching/adminas a route. - Use
URLSearchParamsfor exact query key/value lookups: Substring checks can match partial parameter names or values unintentionally.
3. SPA Routing, Percent-Encoding, and URL Pitfalls
Keep these browser URL behaviors in mind when checking substrings on active pages:
- Single-Page Applications (React Router / Vue Router / History API) update
locationwithout full reloads: Call your check inside route/navigation effects or event handlers rather than assuming a single initial page-load check stays current. - Percent-encoding alters raw characters in URLs: Spaces, non-ASCII characters, or special symbols may appear encoded (such as
%20or%2F) inlocation.hreforlocation.pathname. - Use
Maprather than plain objects for dynamic segment lookups: Avoids collisions withObject.prototypekeys.
