2

I'm trying to get the query string from a string (not the current URL).

For example, I have a URL 'www.google.com/?query=string', I'd like to be able to run a function on it and get '?query=string' back from it. How would I go about doing this?

Thanks

2
  • Do you need to parse the query string also? Eg to get an object with obj.query == 'string' back? Commented Mar 16, 2010 at 14:56
  • Hi, No i'm just after the full query string, it's for an SEO reporting tool I'm working on. I think Alsciende's answer is what I am after. Commented Mar 16, 2010 at 14:57

4 Answers 4

6

Well, you can use a quick regexp that gets you the part you need:

myString.match(/(\?.*)/)[1]

Example:

'www.google.com/?query=string'.match(/(\?.*)/)[1] // evaluates to '?query=string'
Sign up to request clarification or add additional context in comments.

Comments

2

Window.location.search will evaluate to this.

http://www.w3schools.com/jsref/prop_loc_search.asp

Comments

1

There's a jQuery plugin for that.

2 Comments

He said "not the current URL".
From what I've read in the documentation, you don't have to use the current URL. Maybe I read it wrong, or it's unclear, but this is what it says: "You can create a new query object based on a provided url through the load method," which sounds to me like you can pass in whatever string you want.
0

If you're using jQuery, use this plugin: http://projects.allmarkedup.com/jquery_url_parser/ This one lets you operate on the document's url, or any URL string

Then you can do:

$.url.setUrl("www.google.com/?query=string").attr("query") // returns 'query=string'

Or also get a specific parameter:

$.url.setUrl("www.google.com/?query=string").param("query") // returns 'string'

But if you really just need the whole query string, a quick regex like Alsciende suggested is the way to go.

1 Comment

Hi, Thanks for your response, It was indeed just the whole query string I wanted, but I'm sure I'll need this plugin at some point, so thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.