簡體   English   中英

Node.js 如何按索引拆分查詢字符串值

[英]Node.js how to split querystring value by index

我試圖弄清楚如何在 Node.js 中拆分查詢字符串的值。 這是針對我正在創建的 web 代理。 例如,我需要將查詢字符串拆分為第三個“/”。 https://example.org/bahahhaahhttps://example.org 如果我知道如何按最后一個拆分,例如https://example.org/bahhaa/s2.htmlhttps://example.org/bahhaa . 我想讓這兩個輸出保存到 cookie 中。 例如,我不確定要放置什么代碼。 如果我不夠清楚,請告訴我。

您正在尋找的是內置 Node.js 模塊URL 它將解析出問題的答案,因此您可以獲得路徑名。 然后,您可以.split路徑名來查找您要查找的內容:

const url = require('url');
const URLparts = url.parse('https://example.org/bahahhaah').pathname.split('/');

console.log(URLParts); // yields [`bahahhaah`]

URLParts現在生成一個路徑部分數組,由 URL 末尾的 / 分隔。

您可以使用此 function(閱讀評論以了解其工作原理):

 function removeLastOne(str) { return "https://" + str.replace("https://", "") // remove https.split("/") // split by slash to make it array.slice(0, -1) // remove last item in the array.join("/") // join array to make url } console.log(removeLastOne("https://example.org/bahahhaah")); console.log(removeLastOne("https://example.org/bahahhaah/s2.html"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM