Carl Hopwood
Carl Hopwood

Reputation: 43

Function '.test' in JavaScript. Testing for a variable

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

Answers (3)

Matti Mehtonen
Matti Mehtonen

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

Yogendra Singh
Yogendra Singh

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

Denys Séguret
Denys Séguret

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

Related Questions