MHS
MHS

Reputation: 2350

How to search for multiple texts in a string, using java script?

I have a string, an array of words to be searched for:

strng = "I have been working here since last six months"
text = ["since", "till", "until"]
result = "since"

I want to search for every word in array, in strng and when any of it is found in the strng, it must be assigned to result. how to do it?
I am using .search() for searching a single word, but how to search for multiple words? please help.
I am a Newbie.

Upvotes: 8

Views: 25469

Answers (5)

schnill
schnill

Reputation: 955

I think regular expression is the simple solution for that. Use match() instead of search().

if you write it as,

strng = "I have been working here since last six months"
text = /(since)|(till)|(here)/
result= strng.match(text); // result will have an array [since,since,]

correct solution is to write,

result=strng.match(text)[0];

Upvotes: 3

Premshankar Tiwari
Premshankar Tiwari

Reputation: 3106

Do it like this...

strng = "I have been working here since last six months";
text = ["since", "till", "until"];
results = [];   // make result as object

     for(var i=0; i<=text.length; i++){
          if(strng.indexOf(text[i]) != -1)
             results.push(text[i]);
     }

To make indexOf work in IE, put this code in your script

if (!Array.prototype.indexOf) {

    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    };

}

Upvotes: 1

joerx
joerx

Reputation: 2088

You can either loop over your array of keywords or use a regular expression. The former is simple, the latter is more elegant ;-)

Your regex should be something like "/since|till|until/", but I'm not 100% sure right now. You should research a bit about regexes if you're planning to use them, here's a starter: http://www.w3schools.com/js/js_obj_regexp.asp

EDIT: Just tried it and refreshed my memory. The simplest solution is using .match(), not search(). It's boils down to a one-liner then:

strng.match(/since|till|until/) // returns ["since"]

Using .match() gives you an array with all occurrences of your pattern, in this case the first and only match is the first element of that array.

Upvotes: 14

999k
999k

Reputation: 6565

You can loop through each item in text with .search() like this

for (var i=0; i < text.length; i++)
{
   if (-1 != strng.search(text[i]))
   {
      result = text[i];
      break;
   }
}

Upvotes: 1

BeNdErR
BeNdErR

Reputation: 17929

You can do like this:

var result;
for(var x = 0; x < text.length; x++){
    if(strng.indexOf(text[x]) > -1){
        result = text[x];
        break;
    }
}
alert(result);

working example here: http://jsfiddle.net/j5Y5d/1/

Upvotes: 0

Related Questions