bomortensen
bomortensen

Reputation: 3396

JavaScript string search

I'm trying to search a string for any word of another string with javaScript. Let's say I have the following string that I want to search in:

"Oxford Street 100 London"

And my search term is like this:

"oxford london"

The above searchterm should give me a match since oxford and london is a part of the string to search in.

I have tried str.indexOf("oxford london") !== -1 but that doesn't work since it's not a combined word in the string to search in.

Is there any way of doing this?

Upvotes: 0

Views: 524

Answers (4)

Billy Moon
Billy Moon

Reputation: 58531

mystring = "Oxford Street 100 London"
search = "oxford london"
// split search string, by space, or by another delimiter if you like
terms = search.split(" ")
matches = false
// loop through all terms, assuming that matches is true if no negative comparisons are made
for(i=0; i< terms.length; i++){
  // make sure you lowercase both search string, and comparison string
  if(mystring.toLowerCase().indexOf(terms[i].toLowerCase())){
    matches = true
  }
}
// matches is true if any terms are found, and false if no term is found

Upvotes: 1

Nolo
Nolo

Reputation: 886

This works:

var str = "Oxford Street 100 London";
var terms = "oxford london";
terms = terms.replace(" ", "|");          // "oxford|london"
var find = new RegExp(terms, "g");        // /oxford|london/g
alert(str.toLowerCase().match(find));     // ["oxford", "london"]

see this fiddle.

Upvotes: 0

jgillich
jgillich

Reputation: 76209

I would just use a simple regular expression:

if("London, Oxford street".match(new RegExp("oxford london".split(/\W+/).join("|"), 'i'))) {
    alert("found");   
}

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

You need to split the search terms by a space and search for each (case inensitively, I presume)

var terms = terms.split(' '),
    match = terms.every(function (term) {
        return str.toLowerCase.indexOf(term) > -1;
    });

Upvotes: 1

Related Questions