Javascript regex 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 regular expression does not work as expected, s will never be set ( s = null always) Any ideas?

+4
source share
6 answers
 var regex = new RegExp("^" + name); 

Perhaps this fixes the problem.

+4
source

Since your template is dynamically generated through string concatenation, you need to create a RegExp object:

 var regex = new RegExp('^' + name + '); 
+2
source

You need to use a RegExp object if you want to combine the query string. Therefore, in your case / are part of the request.

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

There are two ways to create a regular expression:

1) Using the literal form

 var re = /\w+/; 

2) Using the object creation form

 var re = new RegExp("\\w+"); 

Usually you need a literal form. In your case, if you create it from a string, you should use the object creation form.

 var re = new RegExp("^" + name); 
+1
source

Just removing slashes works.

 pattern = function(name){"^"+name;} (name + "whatever").match(pattern(name)); // not null ("whatEver..NotName").match(pattern(name)); // null 
0
source

I created jsFiddle so you can test various aspects of the regex.

The problem is that var regex formatting is wrong. Remove / es:

 // Test code var name = "foobar"; //var test = "foobar at the start of a sentence"; var test = "a sentence where foobar isn't at the start"; //var regex = '/^' + name + '/'; // Wrong format var regex = '^' + name; // correct format var s = ''; //s = this.innerHTML.toString().toLowerCase().match(regex); s = test.toString().toLowerCase().match(regex); if (s != null) { //do stuff alert("works"); } 
0
source

Source: https://habr.com/ru/post/1500918/


All Articles