0

I am searching a list of string in a specific long string.

Imagine the long stream is :Jim participates in a free wrestling competition

and the array is :["Jim","free","not","me","you","wrestling"]

the problem is that i want just the names to be retrieved not the other part.

in the up example i need just "Jim" and not "free" or "wrestling".

by the way, the name can be in any position of array.

this is my code.

    title = document.getElementById("title").value
    cat_list = document.getElementById("category-all").textContent.replace(/\n\n/g, "\n").replace(/^\s*/g, "").trim().split("\n");
    for(i = 0; i < cat_list.length; i++){
        if(title.indexOf(cat_list[i]) > -1){
            return cat_list[i]
        }
    }

how can i insert this condition to my code?

2 Answers2

0

Assuming the thing you call name is just a string and you seek the intersection:

var str = "Jim participates in a free wrestling competition"

var arr1 = ["Jim","free","not","me","you","wrestling"]
var arr2 = str.split(" ")

array1.filter((n) => array2.includes(n))

See this question for more.

If you are looking for special names (like person names) there is no way other than checking if it is title case; but any name being the first word of the sentence is title case. So, it breaks your case.

vahdet
  • 6,357
  • 9
  • 51
  • 106
  • OP said it shouldn't match "free" or "wrestling", so I'm not sure this is the solution. – Federico klez Culloca Jan 24 '18 at 09:59
  • Well, first part of the answer is an assumption; and that is what I also mean on the second part. And yes, there is no feasible solution for this question indeed -apart from keeping and maintaining a name file/array etc. – vahdet Jan 25 '18 at 11:48
0

You can find the index of the element you want in the array and then get it like this in ES6:

const cat_list = ["Jim","free","not","me","you","wrestling"];
let nameIndex = cat_list.findIndex(x => x.toString().trim().toUpper() === 'JIM'); 
//instead of hardcoding try to find a way to generalize it like cat_list[name] or something
const name = cat_list[nameIndex];
izengod
  • 1,116
  • 5
  • 17
  • 41