0

Im trying to find a patterns in the sentence for regex matching.. in the code below result contains a string and we are checking if the word apple is present in it.

    var patt = /apple/gi;
    var newResult = patt.test(result);

I found the above code from a used case.. But i was wondering if i have more than one values and i want to check it in the string result, lets say an array with values var arr=["apple", "orange"] var patt=/arr[0]/gi will not work.. what could be the way in that scenario??

2 Answers 2

2

To check multiple entries, you can use the OR operator:

var patt = /apple|orange/gi;
var newResult = patt.test(result);

if you have a variable, you can do the below, IF(!) your key is regexp safe of course (that is, it doesn't contains characters which have meaning in regexp syntax):

var key = "apple";
var patt = new RegExp(key, 'gi');
var newResult = patt.test(result);

Although in this case, you might as well use indexOf:

var key = "apple";
var newResult = result.indexOf(key) > -1;
Sign up to request clarification or add additional context in comments.

3 Comments

no i was wondering what if the string is stored in a variable.. like var key="apple"; /key/gi will not work
ive changed the title to avoid confusion
Ah sorry, I had misunderstood the question, I've edited my answer
0

To use a string for your regex expressions, you need to create the regex using the regex constructor.

var pattern = "apple|orange";
var regex = new RegExp(pattern, "g");    // g is for global match

Read more about it here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Comments

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.