user3399326
user3399326

Reputation: 973

How to return a string that contains specific match?

I am trying to return a string that exactly matches: "Item1_20". I have 1 as the Item_no and 20 as the item_size.

var str = ["Item1_20","Item2_20","Item3_30"....];
var Item_no = 1;  
var Item_size = 20;
for (var i=0; i<str.length; i++)
{
var match = str.match(/Item_no + '_' + Item_size/g);
}

So match should be returned only if it exactly matches "Item1_20".

Upvotes: 1

Views: 34

Answers (3)

PeterKA
PeterKA

Reputation: 24638

Array.indexOf(string) returns the index of string in the array, -1 if not found index > -1 returns true if string was found in Array.

var match = str.indexOf('Item' + Item_no + '_' + Item_size) > -1;

And here is a demo:

var str = ["Item1_20","Item2_20","Item3_30"];
var Item_no = 1;  
var Item_size = 20;
var item_index = str.indexOf('Item' + Item_no + '_' + Item_size);
var match = item_index > -1;
alert( 'Found: ' + item_index + '\nIndex: ' + match );

Upvotes: 0

epascarello
epascarello

Reputation: 207511

You should be using indexOf

str.indexOf(Item_no + '_' + Item_size)

so if you get -1, there is no match.

If you want to use a regular expression, that is not how you build one. You would do it with new RegExp(Item_no + '_' + Item_size,"g") and your loop is NOT comparing each index.

Upvotes: 1

juvian
juvian

Reputation: 16068

How about:

var match = (str[i] == "Item"+Item_no+"_"+Item_size);

No real need to use regex if you want an exact match. Be careful that str is the array, str[i] is the string

Upvotes: 1

Related Questions