Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex match not working

I have the following Javascript regexp:

 var regex = '/^' + name + '/'; 
 var s ='';
 s = this.innerHTML.toString().toLowerCase().match(regex);
    if (s != null){
         //do stuff
    }

This regex does not work as expected, s never gets set (s = null always) Any ideas?

like image 354
Octavian Epure Avatar asked Sep 06 '13 11:09

Octavian Epure


People also ask

How to match RegEx pattern in JavaScript?

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .

How to escape in RegEx JavaScript?

* + ( ) literally, we need to prepend them with a backslash \ (“escape them”). We also need to escape / if we're inside /.../ (but not inside new RegExp ). When passing a string to new RegExp , we need to double backslashes \\ , cause string quotes consume one of them.

What is matchAll in JavaScript?

matchAll() The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups.

How do you get the matching characters in a string in JS?

match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string.


1 Answers

var regex = new RegExp("^" + name);

Maybe this fixes the issue.

like image 115
Dragan Okanovic Avatar answered Sep 21 '22 23:09

Dragan Okanovic