12

I was wondering if I can remove everything after a question mark in a URL?

http://www.site.com?some_parameters_continue_forever

can I just use .remove()? What would need to be put inside the parameters?

Thanks

hellomello
  • 8,219
  • 39
  • 151
  • 297

4 Answers4

12

Since the url is controlled by the browser when you change the url the page will reload. Still for what you want to do, on pages where you don't need the stuff after the ? mark type..

window.location = "http://www.mysite.com" //or whatever your site url is

To dynamically do this you can use the below function and then use window.location

function getPathFromUrl(url) {
  return url.split("?")[0];
}

Note: When you change the url the page will refresh.

LoneWOLFs
  • 2,306
  • 3
  • 20
  • 38
  • One thing to note (even if the answer is correct): yes it is valid to have more than one question mark in a URL, see http://stackoverflow.com/questions/2924160/is-it-valid-to-have-more-than-one-question-mark-in-a-url so if you want the rest of the url string, you cannot "just" use `url.split("?")[1];` – Adriano Oct 30 '14 at 14:13
  • Btw, the solution to get the rest of the url string (containing all params) would be: `url.substring( url.indexOf('?')+1 );` – Adriano Oct 30 '14 at 14:28
6

You can use this simple regex:

yourUrl.replace(/\?.+/, '')

reomve() is for DOM stuff.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
5

Try this snippet:

var url = "http://www.somexample.com?a=b&c=2&d=3";
url = url.substring(0 , url.indexOf('?')+1);
bluish
  • 26,356
  • 27
  • 122
  • 180
amd
  • 20,637
  • 6
  • 49
  • 67
  • would it be possible if I can add on more than just `?`, say it will check `?` or another letter such as `&`? – hellomello Jul 17 '12 at 04:43
  • i was wondering if in replacement there is no `?` and instead it is a `&` instead. I was wondering if it is possible to do such a thing like `url.indexOf('?','&')+1)` – hellomello Jul 17 '12 at 20:13
2

Posting this that worked for me in Python 3 as some of the other solutions didn't.

import re

mystring = 'http://www.example.com?some_parameters_continue_forever'
mystring_clean = re.sub(r'\?.*', '', mystring)

print(mystring_clean)
M3RS
  • 6,720
  • 6
  • 37
  • 47