Javascript Regex Match()
Solution 1
You can simplify your regex a little so it only checks for H
or V
.
regarding the number, you need to remember that match
returns an Array, so you'll need to get the value by index. Also, you shouldn't need the capture group.
And actually, you should really just use one regex.
get100YardVersionEugene: function(spot)
{
var parts = spot.match(/(H|V)([0-9]+)/);
if (parts) {
if (parts[1] == "H")
{
return 100-(+parts[2] || 0);
}
else //V
{
return +parts[2];
}
}
},
Solution 2
Try wrapping yard in [parseInt][1]
.
var yard = parseInt(spot.match(/([0-9]+)/), 10);
Solution 3
The result of the match function is an array. Do this :
var team = spot.match(/[A-Z]+/)[0];
And you also need to parse the result as int.
Alternatively, it doesn't seem like regex are really needed here :
var team = spot.substring(0, 1);
var yard = parseInt(spot.substring(1), 10);
return team=='H' ? (100-yard) : yard;
Solution 4
regexp is total overkill for this. Try String.charAt() or String.substr():
get100YardVersionEugene: function(spot)
{
var team = spot.charAt(0);
var yard = parseInt(spot.substr(1,2), 10);
...
}
Demo: http://jsfiddle.net/yzq9j/2/
Solution 5
You probably need to convert your yard into number
if( team == H ){
return 100-parseInt(yard);
}
Then might be good to check for convertion validity using isNaN method.
Hope this helps.
Related videos on Youtube
Comments
-
ealeon over 1 year
I just want this function to return an int back based on a string but its not working It will be either H or V followed by 1 or 2 digits.
IE: H1 return 99 H09 return 91 H10 return 90 H50 return 50 V1 return 1 V05 return 5 V11 return 11 V50 return 50
spot will be my string thats going in.
get100YardVersionEugene: function(spot) { var team = spot.match(/[A-Z]+/); var yard = spot.match(/([0-9]+)/); if (team == "H") { return 100-yard; } else //V { return yard; } },
for some reason when its V9(or H9) it breaks but when i put in V09 it works.
Can someone tell me why?
EDIT: it breaks as in... I have two variables start and end
so i have something like start = get100YardVersionEugene("V9")
and I use start and end to draw it on html5 canvasstart = get100YardVersionEugene("V9") //doesn't draw correctly start = get100YardVersionEugene("V09") // draw correctly
-
Martin Ender over 11 yearsWhat do you mean by "it breaks"? An error? A wrong result? Which one?
-
Sikshya Maharjan over 11 yearsAnd have you looked at your JavaScript console for any reported errors?
-
Ron Wertlen almost 11 yearsIf you are concerned about performance then don't use regexp for something simple like this, rather use the String routines.
-
-
Denys Séguret over 11 yearsThis doesn't work for "H09". See my answer for the reason : match returns an array.