将精确的字符串与indexOf匹配

时间:2018-11-15 18:35:51

标签: javascript node.js regex string match

说我有这样的东西:

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

我想遍历此字段并找到与“朋友”相匹配的字段,但仅限于朋友-而不是朋友 s ,朋友等。我该怎么做?

我已经尝试过indexOf()和regex匹配,但是我仍然是一个初学者,因此它始终始终与它们匹配。

4 个答案:

答案 0 :(得分:2)

要找到索引,您可以使用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)

答案 1 :(得分:1)

说你有

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') );

答案 2 :(得分:1)

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

docker-compose run newservicenm django-admin.py startproject projectname directoryname

答案 3 :(得分:0)

有几种好的方法可以解决此问题,因为您提到了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]);

相关问题