【问题标题】:What string method for matching specific strings in JavascriptJavascript中匹配特定字符串的字符串方法
【发布时间】:2022-01-07 15:56:39
【问题描述】:

这可能是一个简单的重复问题,但我在下面找不到任何解决我的案例的解决方案。请帮帮我! :)


我正在寻找一种字符串方法来检查值是否与特定字符串匹配并返回该结果。

  • 我正在使用create-react-app,并且我有一个<select> 下拉菜单供用户过滤特定价格范围的菜肴
  • 此下拉列表有 3 个字符串值:“$”、“$$”和“$$$

我目前正在使用.includes 方法,但没有得到我想要的结果,因为它包含了所有包含字符串中的字符的结果。 (如果用户选择“$”,也会返回包含“$$”和“$$$”的结果)

-> 我只希望他们返回与上面字符串值完全相同的结果。 那么用什么来代替.includes 呢?

// Initial states:    
const [foodList, setFoodList] = useState([])
const [foodName, setFoodName] = useState('')
const [isVegetarian, setIsVegetarian] = useState('')
const [priceRange, setPriceRange] = useState('$')

const [textSearch, setTextSearch] = useState('')
const [priceDropdown, setPriceDropdown] = useState('')
const [vegDropdown, setVegDropdown] = useState('')

// Search.js:
    const newSearch = props.foodList.filter((value) => {
            return (
              value.foodName.toLowerCase().includes(textSearch.toLowerCase()) &&
              // What to use instead of .includes here?
              value.priceRange.toLowerCase().includes(priceDropdown.toLocaleLowerCase()) 
              && value.isVegetarian.includes(vegDropdown.toLowerCase())
            )
          }
      )

【问题讨论】:

  • React 和这个有什么关系?给出一个minimal可重现的例子,见minimal reproducible example。但基本上"$$$"确实包括"$"
  • 为什么不完全匹配? priceRange 的值是多少?
  • @jonrsharpe 感谢您的提醒,我已经解决了问题!
  • @epascarello 我在priceRange 上尝试了===,但没有成功。但是下面的解决方案让我也尝试isVegetarian,它现在可以工作了:)

标签: javascript string methods ecmascript-6


【解决方案1】:

看起来标准的=== 足以满足您的需求,因为您不是在检查值是否包含过滤器选择,而是正是 选择。 (我怀疑您也希望在 isVegetarian 选项上使用相同的选项。

const newSearch = props.foodList.filter((value) => {
  return (
    value.foodName.toLowerCase().includes(textSearch.toLowerCase()) &&
    value.priceRange.toLowerCase() === priceDropdown.toLocaleLowerCase() &&
    value.isVegetarian === vegDropdown.toLowerCase()
  )
});

此外,正如 cmets 所提到的,请尽量减少您的示例以重现问题 - 这始终是上下文和简单性之间的平衡。不过,在这种情况下,显示foodList 的小数据结构和newSearch 方法(稍加解释)可能就足够了。

【讨论】:

  • 感谢您的友好评论和简单的解决方案!我单独在priceRange 上尝试了===,想知道为什么它不起作用。但这行得通!
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多