Posts Simple snippet to get query parameters
Post
Cancel

Simple snippet to get query parameters

Simple snippet to get individual parameters from the url.

1
2
3
4
5
6
const getUrlParameter = (name) => {
  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  var results = regex.exec(location.search);
  return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

Usage:

Demo url: ?post=1234&action=edit

1
2
getUrlParameter('post'); // "1234"
getUrlParameter('action'); // "edit"

Source

This post is licensed under CC BY 4.0 by the author.