我正在实现逻辑,根据用户是否输入一系列数字或字母,使用url作为查询参数。如果用户输入数字,则应使用第一个urlLocation
,否则应使用第二个<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;
}
。试图为第一个使用正则表达式,但我不确定如何正确实现该正则表达式。
originalTransaction
JSFIDDLE示例:Link
答案 0 :(得分:5)
只需使用isNaN
检查是否有号码:
var val = $("#imageid").val();
if (isNaN(val)) {
//Not a number!
} else {
//Number!
}
答案 1 :(得分:1)
您可以使用正则表达式,但您可能希望将其更改为包含星号。
您的另一个选择可能是将其转换为数字并查看它是否仍等于自身 -
var val = $("#imageid").val();
if (+val == val) {
答案 2 :(得分:0)
你可能正在寻找类似的东西:
<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;
}
});
正则表达式解释:
^[\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) «$»