The task is as follows. I need to add gett parameters depending on the specified string. For example:

domain.com 

to add a gett parameter you need to put "/" at the end of the line and then merge it with gett parameters.

But if the user specified a link like:

 domain.com/index.php 

then you know right away you can glue without the "/".

If the user specified

 domain.com/rise 

then it will be domain.com/rise?get

If a

 domain.com/rise/ 

that

 domain.com/rise/?get 

Help please identify this moment.

  • I think you need the operator "+" - Darth
  • try this var uri = window.location + "?" + 'getParam = xyz' - Vanya Avchyan
  • think badly I need to determine when to slash and when not. what to add + so clear - WhoIsDT

1 answer 1

If I understand the question correctly, it will be something like that. Slash will be added only if the url does not end with .php or slash.

 function serializeGet(obj) { var str = []; for(var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } function addGet(url, get) { if (typeof(get) === 'object') { get = serializeGet(get); } if (url.match(/\?/)) { return url + '&' + get; } if (!url.match(/\.\w{3,4}$/) && url.substr(-1, 1) !== '/') { url += '/'; } return url + '?' + get; } console.log(addGet('ya.ru', 'a=b')); console.log(addGet('ya.ru/', 'a=b')); console.log(addGet('ya.ru/index.php', 'a=b')); console.log(addGet('ya.ru/index.php?text=12345', 'a=b')); console.log(addGet('ya.ru/index.php?text=12345', {a:"100%", b:"abc", d:128})); 

  • And what if I add console.log (addGet ('ya.ru?xyz=trulyalya', 'a = b')); Correct the functionality and for these cases then there will be norms. This is an inferior code. And it turns out that it is so shorter and optimally
  • Are there any functions to determine the page extension? Suddenly there is html, php, aspx, and so on. I want to universalize the function - WhoIsDT
  • It can be determined regularly by the pattern \.\w{3,4}$ - ilyaplot
  • one
    @ilyaplot sincerely thank you! The function is universal! problem solved!) - WhoIsDT
  • one
    @ilyaplot So you can write a framework :). Well, I think enough. Exhaustive answer. Bravo - Vanya Avchyan