1

I have array of regex pattern, i want to check the url which matches the regex and use it. please let me know the best way to do it.

The code i have written is something like this.

var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = a.exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");

Expected:

when i use a.exec it should parse the url "/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"

and give results.

2 Answers 2

1

Iterate over the regexes like this:

var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = [];
for (var i = 0; i < a.length; i++) {
    result.push(RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"));
}

All matches are then stored in result.

result[0] is a array with matches from the regex in a at index 0, result[1] --> a[1], etc. If there are no results from the regex, result[x] will be null.

Instead of pushing the regex result to a array, you could also work on the result directly:

for (var i = 0; i < a.length; i++) {
    var currentResult = RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
    // Do stuff with currentResult here.
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can loop over your regex array:

var a = [/^\/(.*)\/product_(.*)/, /(.*)cat_(.*)/];
var results = [];

for (var i = 0; i < a.length; i++) {
  var result = a[i].exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
  results.push(result);
}

console.log(results);

2 Comments

You can't exec strings, and you might want to mention you'll be overwriting result each iteration.
@Cerbrus I do not exec strings. In a array there are regex elements.

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.