Match dynamic string using regex

I am trying to detect the appearance of a string in a string. But the code below always returns "null". Obviously, something went wrong, but since I'm new, I can't figure it out. I expect the code to return "true" instead of "null"

var searchStr = 'width'; var strRegExPattern = '/'+searchStr+'\b/'; "32:width: 900px;".match(new RegExp(strRegExPattern,'g')); 
+7
javascript regex
source share
4 answers

Please do not put '/' when you pass a string in the RegExp option

Following would be good

 var strRegExPattern = '\\b'+searchStr+'\\b'; "32:width: 900px;".match(new RegExp(strRegExPattern,'g')); 
+17
source share

The correct tool for this job is not a regular expression, but String.indexOf:

 var str = '32:width: 900px;', search = 'width', isInString = !(str.indexOf(search) == -1); // isInString will be a boolean. true in this case 

Documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf

+4
source share

You are mixing two ways to create regular expressions in JavaScript. If you use a regular expression literal, / is a regular expression delimiter, the g modifier immediately follows the closing delimiter, and \b is the escape sequence for the word boundary:

 var regex = /width\b/g; 

If you create it as a string literal for the RegExp constructor, you will leave the regular expression delimiters, you will pass the modifiers in the form of the second string argument, and you will have to double the backslash in the regular expression escape sequences:

 var regex = new RegExp('width\\b', 'g'); 

As you do this, \b converted to a backspace character before it reaches the regular expression compiler; you need to avoid the backslash in order to get it after processing the JavaScript literal escape string string. Or use a regex literal.

+3
source share

Note that '\\ b' is one slash in the string followed by the letter 'b', '\ b' is the escape code \b that does not exist, and collapses to 'b'.

Also consider escaping metacharacters in a string if you want them to 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 
0
source share

All Articles