0

Okay, may be the question was weird. Let me explain a case in hand. I have 5 names in an array eg:

var namesArray=['John','Henry','Smith','James','Carl'];

And I also have a string from some other operation which contains one of these strings with a salutation, say Hello John or Mr.John (note that there is no space in the second one).

var returnedName='Howdy,James!';

What I do know is that the returning string will contain only one of the strings in the mentioned namesArray and no more, and I have no knowledge about the surrounding characters the string may have in returnedName.

What is the fastest way to know which of the strings in the namesArray is a substring of returnedName? I was expecting a function which returns the index of the string in namesArray which is a substring of returnedName. Does such an in-built function exist? If not, what would be the fastest (I have a namesArray of about 100k names, say) way to do that?

artfuldev
  • 1,118
  • 1
  • 13
  • 25
  • 1
    This would answer your question - http://stackoverflow.com/questions/5296268/fastest-way-to-check-a-string-contain-another-substring-in-javascript – MusicLovingIndianGirl Jan 08 '14 at 10:17
  • if `namesArray` contains `Carl` and the `returnedName` contains `Carlito` - how would you handle that? – georg Jan 08 '14 at 10:26
  • I would still want the index of Carl to be returned, as it is a valid substring. One one valid substring is possible in my case, the names were just a way to give an example. – artfuldev Jan 08 '14 at 10:28

4 Answers4

2

This seems to be more like a searching problem. Obviously, while searching you do need to make a comparison to match your search term. For this w.r.t. your problem, in JavaScript you can think of Regex and indexOf. But to make it faster for better time complexity you'll have to think of some better search algorithm (Binary Search may be) than a linear iteration over array.

Niranjan Borawake
  • 1,628
  • 13
  • 20
1

There are multiple ways to check if string contains another substring.

var str = "Hello world, welcome to Javascript Coding.";
var n = str.indexOf("welcome");

//Returns Index no 13

var s = "foo";
console.log(s.indexOf("oo") > -1)

//returns true

You could also use string.includes method to achieve the same result

var str = "Hello World, Welcome to Javascript Coding";

console.log(str.includes("Welcome to"));    // true
console.log(str.includes("Javascript")); // true
console.log(str.includes("To be", 1)); // false  

Reference article How to check if string contains another substring

0

You have to iterate over the array, checking if the string contains the array value, and if it does, break the loop (as there can be only one) and set a variable :

var containsName = '';

for (var i=0; i<namesArray.length; i++) {
    if ( returnedName.indexOf( namesArray[i] ) != -1 ) {
        containsName = namesArray[i];
        break;
    }
}

alert( containsName );

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388