You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中判断URL是否以数组内的模式结尾?

解决方案:优化页面URL匹配逻辑以设置margin样式

原代码的问题

你尝试用endsWith的写法存在几个关键问题:

  • endsWith仅接受单个字符串参数,无法通过展开运算符传递数组进行多匹配
  • 后缀数组混合了正则表达式与字符串类型,而endsWith不支持正则匹配
  • 数组存在语法错误:'/abc/' '/def/'之间缺少逗号,会直接导致代码报错

可行实现方案

方案1:字符串后缀遍历匹配

如果仅需匹配URL结尾的固定字符串,可遍历后缀数组逐一校验:

const location = useLocation();
const [margin, setMargin] = useState('36px');

// 统一用字符串定义需要匹配的路径后缀
const targetSuffixes = ['/abc/', '/xyz', '/123/', '/456/', '/def/'];

useEffect(() => {
  const currentURL = window.location.href;
  // 检查当前URL是否匹配任意一个目标后缀
  const shouldSetLargeMargin = targetSuffixes.some(suffix => currentURL.endsWith(suffix));
  setMargin(shouldSetLargeMargin ? '350px' : '36px');
}, [location.pathname]);

方案2:正则表达式匹配

如果需要更灵活的匹配规则(比如忽略结尾斜杠、匹配动态路径片段),可使用正则数组:

const location = useLocation();
const [margin, setMargin] = useState('36px');

// 定义正则规则:匹配路径结尾为abc/、abc、xyz、123/等场景
const targetPatterns = [/\/abc\/?$/, /\/xyz$/, /\/123\/?$/, /\/456\/?$/, /\/def\/?$/];

useEffect(() => {
  // 直接用location.pathname,避免域名、端口等环境差异干扰
  const currentPath = location.pathname;
  const shouldSetLargeMargin = targetPatterns.some(pattern => pattern.test(currentPath));
  setMargin(shouldSetLargeMargin ? '350px' : '36px');
}, [location.pathname]);

方案3:react-router路由精准匹配(推荐)

如果你使用react-router,可直接用matchPath做专业的路由匹配,适配复杂路由场景:

import { useLocation, matchPath } from 'react-router-dom';
const [margin, setMargin] = useState('36px');

// 定义需要匹配的目标路由
const targetRoutes = ['/abc', '/xyz', '/123', '/456', '/def'];

useEffect(() => {
  const currentPath = location.pathname;
  const shouldSetLargeMargin = targetRoutes.some(route => 
    matchPath({ path: route, end: true }, currentPath)
  );
  setMargin(shouldSetLargeMargin ? '350px' : '36px');
}, [location.pathname]);

优化建议

  • 优先使用location.pathname替代window.location.href,规避域名、端口、查询参数等环境差异带来的匹配问题
  • 若匹配逻辑需多处复用,可将其封装为自定义Hook,提升代码可维护性

内容的提问来源于stack exchange,提问作者Krish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:35:31