0

so I am trying to search a string for a sub string, and apparently, I must use regular expressions with the .search function, this is the code I have

var str = items[i].toLowerCase;
var str2 = document.getElementById("input").value.toLowerCase;

var index = str.search(str2);

Obhiously this doesn't work and I get an error, saying str.search is not a function, how would I go about changing these two strings into regular expressions?

thanks

1
  • 1
    str and str2 are both pointing to the function toLowerCase, is this a typo, or did you forget to actually call them? (...toLowerCase()) Commented Apr 28, 2011 at 11:26

4 Answers 4

2

Use this:

new RegExp("your regex here", "modifiers");

Take a look into: Using a string variable as regular expression

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

Comments

0

add braces to your function calls:

var str = items[i].toLowerCase();
var str2 = document.getElementById("input").value.toLowerCase();
var index = str.search(str2);

otherwise type of "str" is a function, not result of function execution

Comments

0

your problem is forgetting a set of brackets () -- and as such str and str2 get assigned a function rather than the result of calling that function! Simply change the code:

var str = items[i].toLowerCase();
var str2 = document.getElementById("input").value.toLowerCase();

var index = str.search(str2);

Comments

0

To use an expression in a RegExp constructor:

var re = new RegExp(str, 'g');

will create a regular expression to match the value of str in a string, so:

var str = 'foo';
var re = new RegExp(str, 'i');

is equivalent to the RegExp literal:

var re = /foo/i;

You can use any expression that evaluates to a valid regular expression, so to match foo at the start of a string:

var re = new RegExp('^' + str, 'i');

The only niggle is that quoted characters must be double quoted, so to match whitespace at the end of a string:

var re = new RegExp('\\s+$');

which is equivalent to:

var re = /\s+$/;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.