2

I want to create a regex pattern which should be able to search through an array.

Let's say :

var arr = [ "first", "second", "third" ];

var match = text.match(/<arr>/);

which should be able to match only

<first> or <second> or <third> ......

but should ignore

<ffirst> or <dummy>

I need an efficient approach please .

Any help would be great . Thanks

1
  • I want to match tags which are enclosed within angular brackets and highlight them but the text inside brackets should be in the array. Commented Apr 21, 2014 at 13:52

2 Answers 2

4
  1. First you can do array.map to quote all special regex characters.
  2. Then you can do array.join to join the array elements using | and create an instance of RegExp.

Code:

function quoteSpecial(str) { return str.replace(/([\[\]^$|()\\+*?{}=!.])/g, '\\$1'); }

var arr = [ "first", "second", "third", "fo|ur" ];
var re = new RegExp('<(?:' + arr.map(quoteSpecial).join('|') + ')>');
//=> /<(?:first|second|third|fo\|ur)>/

then use this RegExp object:

'<first>'.match(re); // ["<first>"]

'<ffirst>'.match(re); // null

'<dummy>'.match(re); // null

'<second>'.match(re); // ["<second>"]

'<fo|ur>'.match(re); // ["<fo|ur>"]
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome, and a great question +1. And sorry I got a call in between to could not submit desired edit in time.
3

You should search for a specific word from a list using (a|b|c).

The list is made from the arr by joining the values with | char as glue

var arr = [ "first", "second", "third" ];

var match = text.match(new RegExp("<(?:"+arr.join("|")+")>")); //matches <first> <second> and <third>

Note that if your "source" words might contain regular expression's preserved characters - you might get into trouble - so you might need to escape those characters before joining the array

A good function for doing so can be found here:

function regexpQuote(str, delimiter) {
  return String(str)
    .replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}

so in this case you'll have

function escapeArray(arr){
    var escaped = [];
    for(var i in arr){
       escaped.push(regexpQuote(arr[i]));
    }
    return escaped;
}

var arr = [ "first", "second", "third" ];
var pattern = new RegExp("<(?:"+escapeArray(arr).join("|")+")>");
var match = text.match(pattern); //matches <first> <second> and <third>

1 Comment

Don't forget to ensure arr isn't containing | and similar functional characters before compiling this way.

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.