【问题标题】:How to match a string if it ends differently?如果字符串结尾不同,如何匹配它?
【发布时间】:2023-01-24 23:37:54
【问题描述】:

我有一个导航链接列表。当我在某个页面上时,应突出显示该导航链接。我还希望页面向上(仅)一个级别也突出显示其导航链接,因此:

所有页面:/blogs、blogs/careers、blogs/authors

页面:/博客/作者 突出显示:/blogs/author, /blogs

页面:/blogs/author/Lauren-Stephenson 亮点:/blogs/author/Lauren-Stephenson, blogs/authors 我是这样做的:

import React from 'react';

const navlinks = ["/blogs", "blogs/careers", "blogs/authors"]
const currentPath = "/blogs/authors/Lauren-Stephenson"

export function App(props) {
  return (
    <div className='App'>
     {navlinks.map((links) => 
       <div style={{color: currentPath.includes(links) ? 'green' : 'white'}}>{links}</div>
     )}
    </div>
  );
}

但是我的代码不仅高亮了/blogs/Authors/,还高亮了/blogs,这是不正确的,因为我只想高亮上一级的页面。

我怎样才能做到这一点?

【问题讨论】:

  • 为什么不是/blogs/authors
  • 不明白你的意思。你能否也提供一些例子说明什么应该在什么示例页面上突出显示,以及什么不应该被突出?

标签: javascript


【解决方案1】:

你得到它相反的方式。它被称为:大批.prototype.includes() - 注意“大批”.因此使用数组:

links.includes(currentPath)

但是...鉴于您的 currentPath 是一个更长的路径字符串,您可能还想做:

const navlinks = ["/blogs", "blogs/careers", "blogs/authors"];

const checkNavPath = (path) => navlinks.some(nav => path.startsWith(nav));

console.log(checkNavPath("/blogs"));
console.log(checkNavPath("/blogs/authors"));
console.log(checkNavPath("/blogs/authors/Lauren-Stephenson"));
console.log(checkNavPath("/recipes/food/mashed-potato"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多