如何通过URL获取值,防止输入错误

How to get a value by URL, preventing typos?

本文关键字:输入 错误 何通过 URL 获取      更新时间:2023-09-26

我想从你可以在下面找到的每个URL中获得ID(1337)。最好的方法是什么?ID总是数字。也许分割"/",并采取第一个数值?谢谢你的建议。

实际上URL就像第一个,但我想防止打字错误。

这是JSFiddle: http://jsfiddle.net/vKJfw/

/* outputs "1337" */
var url = "http://www.mydomain.com/module/action/1337/"; 
/* error: outputs "action" */
// var url = "http://www.mydomain.com/module/action/1337";
/* error: outputs "action" */
// var url = "http://www.mydomain.com/module/action/1337#"; 
/* error: outputs "" */
// var url = "http://www.mydomain.com/module/action/1337//";
/* error: outputs "bla" */
// var url = "http://www.mydomain.com/module/action/1337/bla/?x=y";
var url_parts = url.split("/");
var id        = url_parts[url_parts.length-2];
alert(id); // should output "1337" everytime!
var id        = parseInt(url_parts[5]);

适用于你所有的例子。

您也可以使用正则表达式来查找第一个数字:

var reg = /'d+/;
var id = reg.exec(url);

使用正则表达式可能是更健壮的解决方案。