6

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?

1
  • what is this referring here? Commented Sep 6, 2013 at 12:00

6 Answers 6

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

Maybe this fixes the issue.

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

2 Comments

... the two things this answer says are false ... the match function also takes a string, and the pattern is not dynamically evaluated, even with a RegExp
Good to know about the match function. By dynamic, I meant that the pattern required a string concatenation, as opposed to a hard-coded value. The regex object will need to be recreated each time name is updated
1

You need to use RegExp object when you want to concatenate the query string. So in your case the / are part of the query.

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

Comments

1

I created a jsFiddle to allow you to test various regex aspects.

The problem is that the formatting of var regex is incorrect. Remove the /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");
}

Comments

1

There are two ways to create a regular expression:

1) Using the literal form

var re = /\w+/;

2) Using object creation form

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

Typically you will want the literal form. In your case were you are creating it from a string you must use the object creation form.

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

Comments

0

Just removing the slashes works.

pattern = function(name){"^"+name;}

(name + "whatever").match(pattern(name)); // not null
("whatEver..NotName").match(pattern(name)); // null

Comments

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.