Javascript - Get query string from a string? - javascript

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

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'

Window.location.search will evaluate to this.
http://www.w3schools.com/jsref/prop_loc_search.asp

There's a jQuery plugin for that.

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.

Related

How to get an Id out of a Url client side?

If I have a URl like "/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d" what would be the best way to get the ID "2c02ds92-25cb-43e1-9bba-3bd5604a0a3d" out of the URL client side?
I need to be able to build a $.getJSON request with the ID and I'm looking for the cleanest way to do it using JavaScript, jQuery, etc. Thanks
$.getJSON('/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d')...
Use regular expressions and extract the appropriate part (which seems to be UUID) from the URL.
The alternative is to just split the string by / and get last element.
EDIT: The example on how to retrieve UUID from the URI:
var url = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d';
var pattern = /[\da-f]{8}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{12}/;
var match = url.match(pattern)[0];
url.match(pattern) returns array of matches, so assuming there is at least one, and only one match, you should pick it (using [0], as in the example).
Proof: http://jsfiddle.net/p6zud/2/
EDIT 2: Shortened the pattern used for matching (see revision history for comparison).
If the id is always going to be the last section of the URI, you could do something like
var url_array = document.location.split('/');
var id = url_array[url_array.length - 1];
using split, convert the url to an array of parameters. Then last array item in your case would be your ID.
there are very sophisticated URL parsers out there for javascript, perhaps you should look around on google for one that suits your needs.
The simpliest:
var id = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d'.split('/User/')[1];
Gives you 2c021192-25cb-43e1-9bba-3bd5604a0a3d;
Try this
alert("/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d".split('/').slice(-1)[0]);

How to parse a JSON with trailing and starting text?

I am looking to create an HTML version of a JSON, through JavaScript(jQuery), specifically the unofficial Google Dictionary JSON (http://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html).
The problem I am facing is that the JSON is not readable because it has this in front of it "dict_api.callbacks.id100(" and is trailed by ",200,null)".
How can I remove this and then put it into a JSON object such that I can attach the elements to the HTML. Thanks in advance.
This is a JSONP response.
It calls a function specified by the callback parameter to give you the response.
You should create a global function to handle the response, and pass its name as the callback.
jQuery will do this for you:
$.getJSON(
"http://www.google.com/dictionary/json?q=test&sl=en&tl=en&restrict=pr%2Cde&client=te&callback=?",
function(response) {
alert(response);
}
)
One thing you can do is write a regular expression (or a pair of them) to do something like:
string.replace(/Regular expression that matches start/, "")
string.replace(/Regulat expression that matches the finish/, "")
Be careful not to use greedy regular expressions if you go this route, I have seen entertaining-but-not-very-helpful results with greed exressions in cases like this.
Otherwise, I would definitely go with the other response by SLaks related to using JQuery, as it should also give you additonal abilities to work with the data later, should your need change after the fact.

javascript regular expression

I want to match some links from a web content. I know I can use file_get_contents(url) to do this in php. How about in javascript?
For regular expression, like
contents
How can I use js regular expression to match this (match only once, do not greedy). I try to use this
/^\<a href=\"someurl\/something\" id=\"someid\"\>(+?)\<\/a\>$/
but it doesn't work.
Can someone help?
Thanks!
You should know that parsing HTML with regex is not the optimal way to solve this problem, and if you have access to a live DOM of the page, you should use DOM methods instead. As in, you should use
document.getElementById('someid').innerHTML // this will return 'contents'
instead of a regex.
I'd highly recommend using a library like jQuery to get the element, and then get the contents via a .text() call. It's much more simple and reliable than trying to parse HTML with regex.
DOM and jQuery suggestions are better but if you still want to use regex then try this:
/^<a href=".*?" id=".*?">(.*?)<\/a>$/
You might as well create the elements with jQuery
var elements = $(html);
var links = elements.find('a');
links.each(function(i, link){
//Do the regexp matching in here if you wish to search for specific urls only
});
In bigger documents, using the DOM is way quicker than regexping the whole thing as text.
Try this~
try {
boolean foundMatch = subjectString.matches("(?im)<a[^>]*href=(\"[^\"]*\"|'[^']*'|[^\\s>]*)[^>]*>.*?</a>");
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
Match double quotation marks,single quotes and empty.
contents
<a href='someurl/something' id='someid'>contents</a>
<a href=someurl/something id=someid>contents</a>

Getting part of referring url with jquery

I'm trying to set a cookie with a value that is made up of part of a referring url. The referring url looks something like:
http://webct.university.ac.uk/webct/urw/lc715920578061.tp721521425061/courseMenu.dowebct?
and I need to extract:
lc715920578061.tp721521425061
for reuse in another function.
Would this be regex? Could anyone help with the syntax?
Many thanks
Matthew
You can use replace with a regex and split like this:
var desired_part = document.referrer.replace(/^https?:\/\//gi, '').split('/')[3];

get query string into js/jquery

i hae a link like ( domain.com/jsapi?key=123456 )
hov can i get this "key" into my JS code? i use jQuery and i don't know about its are easy way to get this "key" into JS variable.
tanks for all.
This plugin might helps: jquery url parser
key = $.url.setUrl($(yourlink).attr('href')).param('key');
(not tested)
It's not jquery. It's pure javascript. You can use regexp.
str = "domain.com/jsapi?key=123456" # Take it from wherever you want
splitted = str.split(/\?key=([0-9]+)/)
Then you'll have an array in the "splitted" variable, it's second element (at the id 1) containing the value.
jQuery not needed. The query string is available from the DOM:
window.location.search.match(/key=([^&]*)/);
Which gives you an array that has your value in it.
You can use the URL constructor as follows:
let url = new URL('https://example.com/jsapi?key=123456');
console.log(url.searchParams.get('key')); // Outputs 123456
Using this method you can parse and get any part of a URL.
Important:
Note that I've added the protocol (https://) to the sample URL so I make sure it is a valid URL and it can be parsed.
Take into account the browser compatibility. You can check it here
For more details you can also the the specification.

Categories

Resources