Partial string matching in javascript

I have this javascript function:

var y;
y = ['ab', 'f', 'c'].indexOf('b')

This returns -1 because b is not a full match against ab In javascript, what is the easiest way of looking for a partial match.

So I want :

y = ['ab', 'f', 'c'].indexOf('b')

to return 0(index of first element because it found a partial match while comparing b to ab

I understand i cannot do it using indexOf, what is the best way to do it?

Answers:

Answer

You will have to loop through the Array:

var arr = ['ab', 'f', 'c']

function find(a, c) {
  for(var i = 0; i < a.length; ++i) {
    if(a[i].indexOf(c) != -1)
      return i
  }
  
  return -1
}

// Example:
document.body.innerHTML = find(arr, "b")

Answer

With ES6 Array.prototype.findIndex and arrow functions:

y = ['ab', 'f', 'c'];
y.findIndex(el => el.indexOf('b') > -1); //0
Answer

You have multiple way, you can use the method Array.prototype.filter:

var testRegex = /b/;
var result = ['ab','f','c'].map(function(item, index) {
      return testRegex.test(item) ? index : null; //return index in the array if found.
}).filter(function(index) {
   return index !== null;  // filter the result and remove all results that are null;
});

result should equal [0];

if you try with an array like this:

['ab', 'cgt', 'abcd', 'cd', 'efb'];

It should return:

[0, 2, 4]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.