ES6 filter an array with Regex

后端 未结 5 2017
清歌不尽
清歌不尽 2020-12-08 21:47

I\'m trying to filter an array that contains a bunch of urls. I need to return the urls that only contain the word \"contact\".

For example there is a link htt

5条回答
  •  春和景丽
    2020-12-08 22:44

    You need to return the truthy / falsy result from filter function.

    const regex = new RegExp("/\b?contact\b?", 'g');
    
    const sites = {
      links: [{
          href: 'http://www.some-site.com/contact-us'
        },
        {
          href: 'http://www.some-site.com/about'
        },
        {
          href: 'http://www.some-site.com/admin'
        }
      ]
    }
    
    const fitered = sites.links.filter((link) => {
      return link.href.match(regex);
    });
    
    console.log(fitered);

提交回复
热议问题