开发者

Convert a string variable to regular expression in java script?

开发者 https://www.devze.com 2023-03-01 12:10 出处:网络
so I am trying to search a string for a sub string, and apparently, I must u开发者_Go百科se regular expressions with the .search function, this is the code I have

so I am trying to search a string for a sub string, and apparently, I must u开发者_Go百科se 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


Use this:

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

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


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


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);


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+$/;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号