-1

I'm implementing logic to use a url for a query parameter, based on whether the user enters a series of numbers or letters. If the user enters a number, the first urlLocation should be used, otherwise the second one should be used. Trying to use a regex for the first one, but I'm not sure how to implement that one correctly.

<input id="imageid" type="text" />

if ($("#imageid").val() == '/[^0-9\.]/') {
    var urlLocation = "http://www.url.com/rest/v1/cms/story/id/" + imageid.value + "/orientation/" + orientation;
} else {
    var urlLocation = "http://www.url.com/rest/v1/cms/story/guid/" + imageid.value + "/orientation/" + orientation;
}

JSFIDDLE EXAMPLE: Link

Matt
  • 1,239
  • 4
  • 24
  • 53

3 Answers3

5

Just use isNaN to check for a number or not:

var val = $("#imageid").val();
if (isNaN(val)) {
    //Not a number!
} else {
    //Number!
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

You could use a regex, although you'd probably want to change it to include a star.

Your other option could be to convert it to a number and see if it is still equal to itself -

var val = $("#imageid").val();
if (+val == val) {
Evan Knowles
  • 7,426
  • 2
  • 37
  • 71
0

You may be looking for something like:

<form id="myForm">
<input id="imageId" type="text" />
<input type="submit">
</form>

$(document).on('submit','#myForm',function(){
if (/^[\d]+$/.test($("#imageId").val())) {
var urlLocation = "http://www.url.com/rest/v1/cms/story/id/" + imageid.value + "/orientation/" + orientation;
} else {
var urlLocation = "http://www.url.com/rest/v1/cms/story/guid/" + imageid.value + "/orientation/" + orientation;
}
});

CODEPEN DEMO

Regex Explanation:

^[\d]+$
-------

Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed, line feed, line separator, paragraph separator) «^»
Match a single character that is a “digit” (ASCII 0–9 only) «[\d]+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of a line (at the end of the string or before a line break character) (line feed, line feed, line separator, paragraph separator) «$»
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268