【问题标题】:How to check if a string contains any element of a list & get the value of the element?如何检查字符串是否包含列表的任何元素并获取元素的值?
【发布时间】:2021-10-31 21:51:16
【问题描述】:

我想确定列表“网站”中的字符串是否包含在另一个字符串“url”中并从列表中获取字符串的值。

下面的代码可以确定是否可以在 'url' 中找到来自 'websites' 的字符串,但无法从列表中获取触发 .some() 的字符串。

我收到以下错误:“ReferenceError: website is not defined”

在发现 'url' 包含一些 'websites' 的值后,有什么方法可以从 'websites' 中获取字符串的值?

websites = [
'google',
'youtube',
'twitter',
]

var url = window.location.href  // e.g. returns www.google.com/soooomethingelse

if (websites.some(website => url.includes(website)))
{
   console.log(website)  // here I want to log 'google' from 'websites'
}

【问题讨论】:

    标签: javascript string list search contains


    【解决方案1】:

    我认为只使用.find 方法会容易得多,该方法在满足箭头函数中的条件时返回元素(箭头函数返回true)。

    websites = [
      'google',
      'youtube',
      'twitter',
    ]
    
    var url = window.location.href // e.g. returns www.google.com/soooomethingelse
    
    var website = websites.find((el) => url.includes(el))
    if (website) {
      console.log(website) // here I want to log 'google' from 'websites'
    }

    【讨论】:

    • 是的,这正是我想要的,非常感谢!
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 2017-11-20
    • 2019-03-16
    • 1970-01-01
    • 2012-08-31
    • 2010-10-04
    • 1970-01-01
    • 2011-12-23
    相关资源
    最近更新 更多