Javascript regular expression to parse path string

老子叫甜甜 提交于 2019-12-01 21:59:09

问题


I have an application that shows photos and albums to a user. Based on current state of the application I show appropriate view. Everytime view changes I change the url, controller then gets the url value using window.location.hash

It returns the string of this form:

"photos/byalbum/albumid"
"photos/allphotos"
"photos/eachphoto/albumid/photoid"

My question is how do I parse this using javscript regular expressions to determine which view I should be showing and also to get the parameters (albumId/photoId)


回答1:


I think you are better off doing this, then regex:

"photos/eachphoto/albumid/photoid".split("/")

Then you get array that you can examine.




回答2:


Rather than using regex, you should probably simply split the string on "/" and examine each piece of the value for the data that you need.

var urlString = <your returned value here>;
var urlPieces = urlString.split("/");

var view = urlPieces[1];
var album = (urlPieces[2]) ? urlPieces[2] : "";
var photo = (urlPieces[3]) ? urlPieces[3] : "";

Then play with your data as you wish. :)



来源:https://stackoverflow.com/questions/15281871/javascript-regular-expression-to-parse-path-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!