0

I am reading query parameters using below method

function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
if (!results) return '';
if (!results[2]) return '';
result = escape(results[2]);
return decodeURIComponent(result.replace(/\+/g, ' '));

URL is in below format http://loalhost:8080?param1=value1+value2

But problem with above method is if either in value1 and value2 contains genuine + character then that character also is replaced with space.

Can someone help me with this issue?

I need approach to solve above issue in plain javascript.

  • 1
    Use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). Don't reinvent the wheel. – Quentin May 23 '22 at 07:31
  • 1
    Use [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) and [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams). Don't use regex here. – adiga May 23 '22 at 07:31
  • "But problem with above method is if either in value1 and value2 contains genuine + character then that character also is replaced with space." — Either you are using URL encoded data where `+` means space, or you are not and a `+` *should* mean a space but the data is wrong. There's no way for code to tell the difference. – Quentin May 23 '22 at 07:31

0 Answers0