【问题标题】:Matching exact string with indexOf使用 indexOf 匹配精确字符串
【发布时间】:2018-11-15 18:35:51
【问题描述】:

假设我有这样的事情:

[
[ 'Friend' ],
[ 'Friendship-' ],
[ 'Friends' ],
[ 'friendly' ],
[ 'friendster' ],
]

我想通过这个找到匹配“朋友”的字段,但只有朋友 - 不是朋友s、朋友ship等。我该怎么做?

我已经尝试过 indexOf() 和正则表达式匹配,但我还是个初学者,所以它现在总是匹配它们。

【问题讨论】:

  • 您开始使用的数据结构是什么。是否应该将它们全部包含在要过滤的更大数组中?它是一个字符串吗?如果您的示例可以在没有语法错误的情况下复制和粘贴,将会很有帮助。
  • 尝试正则表达式^[F|f]riend$

标签: javascript node.js regex string match


【解决方案1】:

要查找索引,您可以使用findIndex()

如果您可能要查找多个,您可以使用filter(),它将返回匹配列表。由于您要匹配 Friend 并且仅匹配 Friend 您可以使用相等 === 进行测试。

以下是findIndexfilter() 的示例:

let arr = [
    [ 'Friendship-' ],
    [ 'Friends' ],
    [ 'Friend' ],
    [ 'friendly' ],
    [ 'friendster', 'Friend' ]
]
// get first matching index
let idx = arr.findIndex(item => item.includes('Friend'))
console.log("Found Friend at index:", idx) // will be -1 if not found

// filter for `Friends`
let found = arr.filter(i => i.includes('Friend'))
console.log("All with friend: ", found)

【讨论】:

    【解决方案2】:

    如果您的数据结构是包含单个字符串项的数组数组,您可以使用filter

    let items = [
      ['Friend'],
      ['Friendship-'],
      ['Friends'],
      ['friendly'],
      ['friendster']
    ];
    
    items = items.filter(x => x[0] === "Friend");
    console.log(items);

    【讨论】:

      【解决方案3】:

      假设你有

      let a = [ [ 'Friend' ], [ 'Friendship-' ], [ 'Friends' ], [ 'friendly' ], [ 'friendster' ] ]
      

      然后:

      let find = (a,w)=>{let i=-1; a.map((x,j)=>{if(x[0]===w) i=j}); return i}
      
      let index = find(a, 'Friend'); // result: 0
      

      如果未找到,则 find 返回 -1

      更新

      这是基于Mark Meyer 答案的较短版本:

      var find = (a,w)=>a.findIndex(e=>e[0]===w);  // find(a, 'Friend') -> 0
      

      let a = [ [ 'Friend' ], [ 'Friendship-' ], [ 'Friends' ], [ 'friendly' ], [ 'friendster' ] ]
      
      var find = (a,w)=>a.findIndex(e=>e[0]===w); 
      
      
      console.log( find(a, 'Friend') );

      【讨论】:

        【解决方案4】:

        有一些很好的方法可以解决这个问题,因为你提到了RegExp 这个例子将使用一个正则表达式和test 方法(它返回一个布尔值)。表达式开头的^ 告诉求值器只查看行以表达式开头的情况。 $ 最后做同样的事情。结合起来,您会得到一条与您的搜索条件完全匹配的行。

        const arr = [
        [ 'Friendship-' ],
        [ 'Friends' ],
        [ 'friendly' ],
        [ 'Friend' ],
        [ 'friendster' ],
        ]
        
        const index = arr.findIndex(([val]) => /^Friend$/.test(val));
        
        if (index === -1) {
          console.log('No Match Found');
          return;
        }
        console.log(arr[index]);

        【讨论】:

          猜你喜欢
          • 2021-10-18
          • 1970-01-01
          • 2015-10-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多