Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 987
MHS Avatar asked May 31 '13 06:05

MHS


1 Answers

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.

like image 73
joerx Avatar answered Nov 09 '22 03:11

joerx