簡體   English   中英

如何將queryString中的逗號分隔符僅在末尾轉換為pipe分隔符

[英]How to turn comma separator in queryString to pipe separator only at the end

所以我目前有一個 API 我正在使用 queryParams。 參數是顏色,我像這樣調用 api:

{apiUrl}?firstQuery=someQuery&colour=Blue,Green

上述請求將從服務器請求具有藍色和綠色的項目。

現在有時顏色會變得有點棘手並給我帶來問題,特別是顏色描述/文本本身中已經有逗號的長顏色。

以下是長/有問題的顏色列表:

const coloursWithCommas = [
    'Red, Blue, Yellow and Green Play of Colour',
    'Red, Green, Blue And Orange Play Of Colour',
    'Orange With Green, Red, Yellow And Blue Play Of Colour',
    'Green, Blue And Yellow Play Of Colour',
    'Purple-Red, White and Blue-Green',
  ];

正如您在我的 API 調用中看到的那樣,我需要一個逗號分隔符才能一次發送多種顏色,但有些顏色中已經有逗號。 因此,此請求無法獲得所需的顏色: {apiUrl}?firstQuery=someQuery&colour=Blue,Green,Red, Blue, Yellow and Green Play of Colour

如您所見,我試圖在 1 個請求中獲得 3 種不同的顏色,即藍色綠色紅色、藍色、黃色和綠色的顏色

為了解決這個問題,API 現在接受 | pipe 分隔符代替逗號發送多種顏色,同時尊重包含逗號的每個顏色值。

所以現在新的 api 調用是:

{apiUrl}?firstQuery=someQuery&colour=Blue|Green|Red, Blue, Yellow and Green Play of Colour|Purple-Red, White and Blue-Green

這將成功返回我Blue , Green , Red, Blue , Yellow 和 Green Play of Color , Purple-Red, White 和 Blue-Green

我寫了這個助手 function:

const convertCommaToPipe = (queryInput) => {
  let queryStringName = queryInput.split('=')[0];
  let queryString = queryInput.split('=')[1];

  const coloursWithCommas = [
    'Red, Blue, Yellow and Green Play of Colour',
    'Red, Green, Blue And Orange Play Of Colour',
    'Orange With Green, Red, Yellow And Blue Play Of Colour',
    'Green, Blue And Yellow Play Of Colour',
    'Purple-Red, White and Blue-Green',
  ];

  if(!coloursWithCommas.includes(queryString)){
    queryString = queryString.replace(',', '|');
  } else{
    const longColourIndex = coloursWithCommas.findIndex((text) => text === queryString);
    queryString = coloursWithCommas[longColourIndex] + '|';
  }

  return queryStringName + '=' + queryString;
}

這樣我就可以從以下位置打開查詢字符串: colour=Blue,Green, Blue And Yellow Play Of Colour,Orange With Green, Red, Yellow And Blue Play Of Colour

至:

&colour=Blue|Green, Blue And Yellow Play Of Colour|Orange With Green, Red, Yellow And Blue Play Of Colour

來自幫助程序 function 的 queryInput 將始終以colour=Bluecolour=Green, Blue And Yellow Play Of Colour開始,然后它會一次構建/附加一個,然后可以進行完整的查詢,例如colour=Blue,Green,Red, Blue, Yellow and Green Play of Colour表明用戶點擊了這 3 種顏色。

它不會一次接收所有顏色查詢,它會在用戶單擊 UI 時附加。 這似乎是導致我的 function 不能完全 100% 工作的原因。 請告知在這種情況下實現我想要達到的目標的最佳方法。

我建議您自行更改 API(假設它是您的 API)。 您應該使用PUTPOST並將 colors 作為字符串數組傳遞。

暫無
暫無

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

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