0

I have something I am trying to accomplish.

I'd like to take an array built with AJAX/xml.

array[/word0/, /word1/, /word2/]

and put this into a form that could be used in a .match():

result = string.match(array)

I have tried using a for loop and stepping through the array using string.match(array[i]) to no avail.

Is there an easy way to do this?

3
  • 2
    string.match(/word0|word1|word2/) Commented Mar 15, 2013 at 22:48
  • What was the error you got? I think you'll have to be more descriptive than "to no avail". What you were doing is a valid solution, so my guess is your problem lies elsewhere (see my answer for a more specific guess). Commented Mar 15, 2013 at 22:56
  • I'm not actually getting any errors. I understand the principle of using your example, however, if I dump the contents of the array prior to the .join I get "word1", "word2", "word3". After the .join I get this: /(?:)/ Commented Mar 16, 2013 at 0:31

3 Answers 3

1

Edit: You may have a syntax problem. The following is not valid syntax:

array[/word0/, /word1/, /word2/]

Something like this fixes it:

var regexps = [/word0/, /word1/, /word2/];

Original answer:

Javascript RegExps already do this. You're looking for:

var regexp = /word0|word1|word2/;

Assuming your list of matches comes back in the right format, you could achieve this like so:

var words = ["word0", "word1", "word2"];
var regexp = new Regexp(words.join("|"));
str.match(regexp);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir. I did indeed have a syntax problem. I had a } cutting off access the original array. Although it took several hours you helped me track it down. Also thanks to the others for the suggestions. Cheers
1

http://jsfiddle.net/KALPh/

Your approach was fine. Here's my implementation:

var regexes = [/^def/, /^abc/],
    testString = 'abcdef',
    numRegexes = regexes.length;

for(var x=0;x<numRegexes;x++) {
    alert(regexes[x].test(testString));
}

Comments

0

To initialize your array, use

var array = [/word0/, /word1/, /word2/];

Then you can use

str.match(array[i])

If your problem is the transmission in "AJAX/xml", then you'll need to build the regular expressions client side with new RegExp(somestring) where somestring might for example be "word0" : you can't embed a regex literal in XML.

1 Comment

Sorry I guess I should have been more precise. I just gave abridged code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.