How to get the filetype of an url string inside a javascript function?
I have two initialization methods: initXML(url) and initJSON(url), which accept an url parameter. The parameter must be an url string that points to an XML or JSON file depending on the function.
What I want to do is to have just one method called init(url) which开发者_Go百科 accepts an url parameter and then calls initXML() or initJSON() based on the filetype of the url parameter string.
e.g. if the url parameter is something like 'content/file.json' call initJSON(), if it is 'other/file.xml' call initXML(), if another filetype return an error.
How can I know this?
Thanks in advance.
Use String.match().
function init(url)
{
if ( url.match(/\.json$/i) )
{
initJSON();
}
else if ( url.match(/\.xml$/i) )
{
initXML();
}
else
{
throw "Unknown file type";
}
}
A very quick way of doing it would be to assume that the only period in your URL is at the end, just before the file type:
var type = url.split('.');
type = type[1];
Then the type variable would be either 'json' or 'xml'.
A more foolproof system would be to use regular expressions:
var type = /\.(xml|json)$/.exec(url);
type = type[1];
You could use a regular expression like this:
var isJSON = /\.json$/i;
var isXML = /\.xml$/i;
if( isJSON.test( url ) == true )
initJSON()
else if( isXML.test( url ) == true )
initXML()
else
return( 'error' );
加载中,请稍侯......
精彩评论