-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

2
  • 1
    What you have there is a string comparison, not a regex. Commented Apr 24, 2015 at 14:57
  • /^\d+$/.test($("#imageid").val()) Commented Apr 24, 2015 at 15:03

3 Answers 3

5

Just use isNaN to check for a number or not:

var val = $("#imageid").val();
if (isNaN(val)) {
    //Not a number!
} else {
    //Number!
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I had tried that previously, but incorrectly. That works, thanks.
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) {

Comments

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) «$»

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.