This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to get GET and POST variables with JQuery?
Get query string values in JavaScript
lets say my site has url http://www.akbrowser.tk/ds/?q=http://www.chess.com&r=http://www.blackle.com
(the two parameters are URLs)
I now want to get two javascript variables on the site, with the values of the two urls. (so the first variable would be the chess.com, and the second would be blackle.com [of course it would have the http and all, but I can only post one hyperlink])
how would I do that?
I saw some other similar questions on this site, and the poster gave a long solution that I didn't understand (I think it had something to do with find a '=' and take everything after it) but in this case it would give "http:// www.chess.com&r=http://www.blackle.com [without the space]" as one of the variables.
I also saw another post with multiple parameters like mine, but the poster gave a long solution so since I didn't understand it, I couldn't really make it do what I wanted it to do.
so can someone help me?
Try this function:
function getQueryParam(href, paramName) {
var query = href.substring(href.indexOf('?')+1);
var params = query.split('&');
for(var i = 0; i < params.length; i++) {
var param = params[i].split('=');
if(param.length > 1) {
if(param[0] == paramName) {
return param[1];
}
}
}
return null;
}
console.log(getQueryParam('http://www.akbrowser.tk/ds/?q=http://www.chess.com&r=http://www.blackle.com', 'r'));
function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
var qString = gup("q");
var rString = gup("r");
What this does is do a regex to find whatever [name] you pass in to the function.
Related
This question already has answers here:
Get querystring from URL using jQuery [duplicate]
(5 answers)
Closed 1 year ago.
I know this question seems to be around a bit, but 90% of the answers point to a solution that is not working for me (indexof > -1).
if ( window.location.href.indexOf("product=3") > -1 || window.location.href.indexOf("product=2") > -1 ) {
alert('success');
}else {
alert('nothing');
}
The problem is that for product 30 this also alerts success.
Is there a simple solution that can detect an exact match in the url query string.
For example
mycoolsite.com/cart/?type=buynow&product=30
How can we check with javascript or jquery if the product equals 30?
Using the following: Get querystring from URL using jQuery
I would suggest the following:
$(function() {
function getUrlVars(url) {
var vars = {},
hash;
if (url.indexOf("?") < 0) {
return false;
}
var hashes = url.substring(url.indexOf("?") + 1)
$.each(hashes.split("&"), function(i, v) {
hash = v.split('=');
vars[hash[0]] = hash[1];
});
//console.log(url, hashes, vars);
return vars;
}
var queryData;
queryData = getUrlVars(window.location.href + "?buynow&product=3");
console.log(queryData);
queryData = getUrlVars(window.location.href + "?buynow&product=3&product=2");
console.log(queryData);
queryData = getUrlVars(window.location.href + "?buynow&product[]=3&product[]=2");
console.log(queryData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="result"></div>
This code has some caveats. As you can see in my tests, if you have multiple items if the same variable name or index, it will overwrite other values. Also it will not read in Arrays. You could add a check for that and write a function to handle the array portion.
If your Query Hash is always more basic, this could work well enough.
Have used the function from this post as recommended by Twisty in the comments and works well.
Get querystring from URL using jQuery
This question already has answers here:
Adding http:// to all links without a protocol
(4 answers)
Closed 8 years ago.
I would like to detect url's that are entered in a text input. I have the following code which prepends http:// to the beginning of what has been entered:
var input = $(this);
var val = input.val();
if (val && !val.match(/^http([s]?):\/\/.*/)) {
input.val('http://' + val);
}
How would I go about adapting this to only append the http:// if it contains a string followed by a tld? At the moment if I enter a string for example:
Hello. This is a test
the http:// will get appended to hello, even though it's not a url. Any help would be greatly appreciated.
This simple function works for me. We don't care about the real existence of a TLD domain to gain speed, rather we check the syntax like example.com.
Sorry, I've forgotten that VBA trim() is not intrinsic function in js, so:
// Removes leading whitespaces
function LTrim(value)
{
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
}
// Removes ending whitespaces
function RTrim(value)
{
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
// Removes leading and ending whitespaces
function trim(value)
{
return LTrim(RTrim(value));
}
function hasDomainTld(strAddress)
{
var strUrlNow = trim(strAddress);
if(strUrlNow.match(/[,\s]/))
{
return false;
}
var i, regex = new RegExp();
regex.compile("[A-Za-z0-9\-_]+\\.[A-Za-z0-9\-_]+$");
i = regex.test(strUrlNow);
regex = null;
return i;
}
So your code, $(this) is window object, so I pass the objInput through an argument, using classical js instead of jQuery:
function checkIt(objInput)
{
var val = objInput.value;
if(val.match(/http:/i)) {
return false;
}
else if (hasDomainTld(val)) {
objInput.value = 'http://' + val;
}
}
Please test yourself: http://jsfiddle.net/SDUkZ/8/
The best solution i have found is to use the following regex:
/\.[a-zA-Z]{2,3}/
This detects the . after the url, and characters for the extension with a limit of 2/3 characters.
Does this seem ok for basic validation? Please let me know if you see any problems that could arise.
I know that it will detect email address's but this wont matter in this instance.
You need to narrow down your requirements first as URL detection with regular expressions can be very tricky. These are just a few situations where your parser can fail:
IDNs (госуслуги.рф)
Punycode cases (xn--blah)
New TLD being registered (.amazon)
SEO-friendly URLs (domain.com/Everything you need to know about RegEx.aspx)
We recently faced a similar problem and what we ended up doing was a simple check whether the URL starts with either http://, https://, or ftp:// and prepending with http:// if it doesn't start with any of the mentioned schemes. Here's the implementation in TypeScript:
public static EnsureAbsoluteUri(uri: string): string {
var ret = uri || '', m = null, i = -1;
var validSchemes = ko.utils.arrayMap(['http', 'https', 'ftp'], (i) => { return i + '://' });
if (ret && ret.length) {
m = ret.match(/[a-z]+:\/\//gi);
/* Checking against a list of valid schemes and prepending with "http://" if check fails. */
if (m == null || !m.length || (i = $.inArray(m[0].toLowerCase(), validSchemes)) < 0 ||
(i >= 0 && ret.toLowerCase().indexOf(validSchemes[i]) != 0)) {
ret = 'http://' + ret;
}
}
return ret;
}
As you can see, we're not trying to be smart here as we can't predict every possible URL form. Furthermore, this method is usually executed against field values we know are meant to be URLs so the change of misdetection is minimal.
Hope this helps.
This is clearly a RTFM issue, but after I did so repeatedly I just can't get the damn thing to work so there are times when asking for help makes sense:
var text = "KEY:01 VAL:1.10,KEY:02 VAL:2.20,KEY:03 VAL:3.30";
var pattern = '/KEY:(\S+) VAL:([^,]+)/g';
//var pattern = '/KEY:(\S+) VAL:(.?+)(?:(?=,KEY:)|$)/g';
//var pattern = '/KEY:(\S+) VAL:(.+)$/g';
//pattern.compile(pattern);
var kv = null;
var row = 0, col = 0;
while((kv = pattern.exec(text) != null))
{
row = kv[1].charAt(0) - '0';
col = kv[1].charAt(1) - '0';
e = document.getElementById('live').rows[row].cells;
e[col].innerHTML = kv[2].slice(0, kv[2].indexOf(","));
}
kv[1] is supposed to give "01"
kv[2] is supposed to give "1.10"
...and of course kv[] should list all the values of 'text'
to fill the table called 'live'.
But I can't get to have pattern.exec() succeed in doing that.
Where is the glitch?
First, the delimiters for the RegExp should be /s, there's no need to put them in ' delimiters. i.e. to get your exec to run properly you should have:
var pattern = /KEY:(\S+) VAL:([^,]+)/g;
Second, you're assigning a boolean to kv which you don't want. The while will obviously only evaluate to true if it's not null so that's redundant. Instead you just need:
while (kv = pattern.exec(text)) {
That should get your code to work as you desire.
the syntax for pattern objects doesn't include quoting, such as:
var pattern=/KEY:(\S+) VAL:([^,]+)/g;
http://www.w3schools.com/jsref/jsref_regexp_exec.asp
It should be
var pattern = /KEY:(\S+) VAL:([^,]+)/g;
http://www.regular-expressions.info/ is a good place to start with.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Pass vars to JavaScript via the SRC attribute
May I know how to read get the p value on js file link like filename.js?p=value with local javascript in the js file? Any function to work like the $_GET['p'] in php? Thanks.
try this:
var tmp = location.href, it;
if (q) it = tmp.substr(q + 1).split('&');
else it = '';
for (var i in it) {
var t = it[i].split('=');
if (t[0] == 'p') {
//do something
break;
}
}
function _GET( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
This will do the equivalent in javascript.
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Get query string values in JavaScript
Use the get paramater of the url in javascript
I have a long list of URLs where in one part of the URL I've got a command such as 'KEY=123'. I would like to find all those keys.
For Example: /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1
How could this be accomplished? My idea was just to search all the 'KEY' words and look for the number next to it - but I guess there is something much quicker for this.
The language of preference would be Javascript.
EDIT:
The URLs are cluttered and can't be extrapolated out of the text easily. a small example of the text:
2011-07-29 01:17:55.965/somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 685ms 157cpu_ms 87api_cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13`
2011-07-29 01:05:19.566 /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 29ms 23cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13
2011-07-29 01:04:41.231 /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 972ms 78cpu_ms 8api_cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13
The Javascript you'd need would be something like -
var text = 'ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1&key=678';
var matches = text.match(/KEY=\d*|key=\d*/g);
for (i=0; i<matches.length; i++) {
alert(matches[i]);
}
If you wanted just the number, you could do something like -
var text = 'ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1&key=678';
var matches = text.match(/KEY=\d*|key=\d*/g);
for (i=0; i<matches.length; i++) {
alert(matches[i].toLowerCase().replace('key=',''));
}
If you are interested only in the KEY value:
var regex = new RegExp("KEY=(\d+)");
var result = regex.exec(window.location.href);
result would be "123" in your case. If you have multiple lines, then:
var regex = new RegExp("KEY=(\d+)", "gm");
var results = regex.exec(window.location.href);
in this case results is an array.
a = "/somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1";
a.match(/KEY\=(\d+)/gi)