請多用正則表示式來解析字串,即簡潔又不易出錯,
畢竟寫程式連基本的正則表示式都不學,而只會用笨方法從字串抓東西,說寫出來的東西有多嚴謹我都不相信。
以下示範二個網頁最常用的parser範例(youtube & query string):
http://jsfiddle.net/24mw91hq/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | youtube url: <textarea id= "youtube_url" style= "width: 400px;" type= "text" >https: //www.youtube.com/watch?v=31JAXPRBawg </textarea> parsing result:<div id= "youtube_result" ></div><hr>query string: <textarea id= "query_string" style= "width: 400px;" type= "text" >a=b&c=d&e=&=f&=&g </textarea> parsing result:<div id= "query_result" ></div><script> function parse_youtube_id(yturl) { return (regexRes = yturl.match( "youtube.com/.*[\\?&]v=([^&#]*)" ) || yturl.match( "youtu.be/([^&#?]*)" )) && regexRes[1]; } function parse_query_string(query){ //query = query || location.search.substring(1); var args = {}, match = [], reg = /([^\?&= #]+)=([^\?&=#]*)/g; while (match = reg.exec(query)){ args[decodeURIComponent(match[1])] = decodeURIComponent(match[2]); } return args; } $( '#youtube_url' ).keyup( function (e){ $( '#youtube_result' ).text(parse_youtube_id($( this ).val())); }); $( '#query_string' ).keyup( function (e){ $( '#query_result' ).text(JSON.stringify(parse_query_string($( this ).val()))); }); $( '#youtube_url' ).keyup(); $( '#query_string' ).keyup(); </script> |
沒有留言:
張貼留言