Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match dynamic string using regex

I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"

var searchStr = 'width'; 
var strRegExPattern = '/'+searchStr+'\b/'; 
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
like image 995
Fares Farhan Avatar asked Jan 27 '10 06:01

Fares Farhan


People also ask

How do I create a dynamic expression in regex?

The key to making the dynamic regex global is to transform it into a RegExp object, and pass 'g' in as the second argument. Working example. Although the new operator isn't required when creating instances of built-in objects, it's still recommended. @AlexandruRada Edited.

What is dynamic regex?

In a dynamic expression, you can make the pattern that you want regexp to match dependent on the content of the input text. In this way, you can more closely match varying input patterns in the text being parsed. You can also use dynamic expressions in replacement terms for use with the regexprep function.

Which of the following options can you use to create a dynamic regex using the string in a variable variable '?

You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String. raw will prevent javascript from escaping any character within your string values.

Can regex take variables?

If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .


2 Answers

Please don't put '/' when you pass string in RegExp option

Following would be fine

var strRegExPattern = '\\b'+searchStr+'\\b'; 
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
like image 121
YOU Avatar answered Oct 06 '22 04:10

YOU


Notice that '\\b' is a single slash in a string followed by the letter 'b', '\b' is the escape code \b, which doesn't exist, and collapses to 'b'.

Also consider escaping metacharacters in the string if you intend them to only match their literal values.

var string = 'width';
var quotemeta_string = string.replace(/[^$\[\]+*?.(){}\\|]/g, '\\$1'); // escape meta chars
var pattern = quotemeta_string + '\\b';
var re = new RegExp(pattern);
var bool_match = re.test(input); // just test whether matches
var list_matches = input.match(re); // get captured results
like image 28
Anonymous Avatar answered Oct 06 '22 06:10

Anonymous