Get the latest key param of multiple params from a single URL?

Viewed 217

When user is in page 'a' and there writes something in forms input field then goes from page a to page b and from there back to page a, here if user wants to get data from url, there could be two with the same name for example this is url ?name=james&name=alex my question is how to get that latest 'name' for example name name=alex is the new one. Here is how i get from url:

const query = window.location.toString().split("?")[1];

const urlParams = new URLSearchParams(query);


const Name = urlParams.get("name") || props.order?.name;
<Form.Item label={t( "orders.name")} name="name" initialValue={Name || ""}>
  <Input type="string" />
</Form.Item>

2 Answers

This answer is adopted from HERE.

You should instead encode your names as an array and set it to the name parameter. When you add a new name, use Array.push(ITEM) to add to the end, and to get the most recently added item use Array[Array.length - 1].

//URL to array:
function URLToArray(url, param) {
    return url.substring(url.indexOf(param + '=') + param.length + 1).split('&')[0].split('_');
}

//Array to URL:
function ArrayToURL(array, param) {
  return param + '=' + array.join('_');
}

/*************************************/

//You can then use this as such:

// Get Array
var myArray = URLToArray('https://google.com?name=Bob_Joe_Tom&state=Alaska_Texas_Main', 'name');

console.log(myArray);

// Get URL
myArray.push('Steph'); //Lets add a name to the array
var myNameUrl = 'www.google.com?' + ArrayToURL(myArray, 'name');


console.log(myNameUrl);

I have made this so you can have any number of arrays on the url as well, hence why I have the state value in the example, just to show it can discern between the two arrays.

May be this will help you.

function getLatestParamFromUrl(param="") {
  const url = new URL(window.location.href);

  const values = url.searchParams.getAll(param);

  const latestValues = values.length > 0 ? values.pop() : false;

  return !!latestValues && latestValues;
}

console.log(getLatestParamFromUrl("name"));

Related