Reputation: 43
I am having issues searching for a variable within a variable. The code that I have is:
var str = "13, 12, 12, 12";
//Look for string = 13 in str.
var string = 13;
var patt = "/" + string + "/g";
var result = patt.test(str);
What is my error?
Upvotes: 2
Views: 515
Reputation: 1705
If you are trying to get indexOf
the first value of 13 in str
, I would do following:
var str = "13, 12, 12, 12";
var string = "13";
var result = str.match(/\d{1,}/g).indexOf(string); //returns 0
This will match only if str
has the value 13. For example, 131 would not match like in your current code. If you are trying to test if the value 13 exists in str
, I would do following:
var str = "13, 12, 12, 12";
var string = "13";
var result = (str.match(/\d{1,}/g).indexOf(string) !== -1); //Returns true
Upvotes: 0
Reputation: 34367
I suggest to use indexOf
function as below:
var str="13, 12, 12, 12";
var string= "13";
var result = str.indexOf(string)>=0;
Upvotes: 2
Reputation: 382150
Use
var patt = new RegExp(string, 'g');
to build your pattern. The /something/g
construct cannot be used for dynamic patterns.
See MDN's documentation on regular expressions.
Upvotes: 5