jsÔõÑù»ñÈ¡urlÖеIJÎÊý
javascript »ñÈ¡ url ²ÎÊýµÄÒªÁìÓÐÒÔÏÂÈýÖÖ£ºwindow.location.search ·µ»Ø url ÖÐÎʺŠ(?) Ö®ºóµÄ²¿·Ö¡£urlsearchparams ¹¤¾ßÌṩÁËÔ½·¢Àû±ãµÄÅÌÎÊ×Ö·û´®´¦Öóͷ£¡£ÕýÔò±í´ïʽ¿ÉÓÃÓÚÆÊÎö url ²ÎÊý£¬µ«Ïà¶ÔÖØ´ó¡£
ÔõÑùʹÓà JavaScript »ñÈ¡ URL ÖеIJÎÊý
JavaScript ÌṩÁ˶àÖÖÒªÁìÀ´»á¼û URL ÖеIJÎÊý¡£
1. window.location.search
window.location.search ÊôÐÔ·µ»Ø URL ÖÐÎʺŠ(?) Ö®ºóµÄ²¿·Ö£¬¼´ÅÌÎÊ×Ö·û´®¡£
ʹÓÃʾÀý£º
const url = "https://example.com/search?q=apple"; const queryParams = url.split("?")[1]; // "q=apple" console.log(queryParams);
µÇ¼ºó¸´ÖÆ
2. URLSearchParams
URLSearchParams ¹¤¾ßÊÇÁíÒ»¸ö»ñÈ¡ URL ²ÎÊýµÄÓÐÓÃÒªÁì¡£ËüÌṩÁËÔ½·¢Àû±ãµÄÒªÁìÀ´´¦Öóͷ£ÅÌÎÊ×Ö·û´®¡£
ʹÓÃʾÀý£º
const url = new URL("https://example.com/search?q=apple"); const queryParams = new URLSearchParams(url.searchParams); console.log(queryParams.get("q")); // "apple"
µÇ¼ºó¸´ÖÆ
3. ÕýÔò±í´ïʽ
ÕýÔò±í´ïʽҲ¿ÉÒÔÓÃÀ´ÆÊÎö URL ²ÎÊý£¬µ«ÕâÖÖÒªÁìÏà¶ÔÖØ´ó¡£
ʹÓÃʾÀý£º
const url = "https://example.com/search?q=apple"; const regex = /q=(.*)/; const queryParams = url.match(regex); console.log(queryParams[1]); // "apple"
µÇ¼ºó¸´ÖÆ
Ñ¡ÔñÄÄÖÖÒªÁ죿
×î¼ÑÒªÁìÈ¡¾öÓÚÄúµÄÏêϸÐèÇóºÍÆ«ºÃ¡£ÔÚ´ó´ó¶¼ÇéÐÎÏ£¬window.location.search ºÍ URLSearchParams ÊÇ»ñÈ¡ URL ²ÎÊýµÄ±ã½ÝÑ¡Ôñ¡£ÕýÔò±í´ïʽҪÁì¸üÊʺÏÓÚÐèÒª×Ô½ç˵ÆÊÎöµÄÖش󳡾°¡£
ÒÔÉϾÍÊÇjsÔõÑù»ñÈ¡urlÖеIJÎÊýµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡