How to extract URL parameters with jquery [duplicate] - javascript

This question already has answers here:
Getting URL hash location, and using it in jQuery
(7 answers)
Closed 8 years ago.
I have somes links like this:
mywebsite.com/tutos.php?name=tuto_name#comments
mywebsite.com/tutos.php?name=tuto_name#download
My question: how to get the text after the #.
thanks.

window.location.hash is a cross browser solution that returns the value (including the hash)
You can remove the hash by doing:
var hash = window.location.hash.substr(1);

I use the following as it not only grabs the hash value (without the hash itself (taking the 2nd part (array[1] of the split)), but also tests the undefined case as well which can cause problems in some cases.
var hashVal = window.location.hash.split("#")[1];
if( hashVal && hashVal != "undefined" ) {
//work it
}

I use the following JS function that will do this:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}

You can use window.location.hash. It takes with # (ie, #comments). To remove trialing # use .substring(1). Example:
var str = window.location.hash.substring(1);
alert(str);

Related

How to check if url query string equals something with javascript (or jquery) [duplicate]

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

How to allow linkify url to allow <x x> after a valid url in chat message [duplicate]

This question already has answers here:
Extract URL from string
(5 answers)
Extracting for URL from string using regex
(3 answers)
Closed 1 year ago.
I have a linkify url text which is in chat message which O needs to allow even <x x> after a valid url. Now when I am using any string after url, it ends up with
InvalidCharacterError: Failed to execute 'createElement' on
'Document': The tag name provided ('x<') is not a valid name.
This should allow
before & after strings Ex: Hi this is test page https://www.test.com as well
Code
sendUrlText(e) {
if (e && e.keyCode && e.keyCode !== 13) return;
var stateMessage = unescape(this.state.message);
function linkify(stateMessage){
return stateMessage.replace(/(https?:\/\/[^\s]+)/g, "<a href='$1' target='_blank'>$1</a>")
}
var formattedMessage = linkify(stateMessage);
}
Any suggestion how can I allow /< x x > after url and turns it into
For example:
with a linkify url.
You mean like this?
function linkify(stateMessage) {
const string = stateMessage.match(/(https?:\/\/[^ ]*)/);
if (!string) return ""
const url = new URL(string[1])
return stateMessage.replace(string[1],`<a href='${url.toString()}' target='_blank'>${url.toString()}</a>`)
}
const link = linkify('Hello, this is a link https://www.test.com/ with a space and valid text')
console.log(link)
document.getElementById("urlOutput").innerHTML = link;
<span id="urlOutput"></span>

Javascript URL Query String Logic

I have an events listing page which can be filtered by type and also by date using query string variables.
I am trying to achieve the following logic using javascript/jQuery.
I have a calendar which fires a function when updated. When fired I need to implement the following logic:
If the current URL contains ?filter= then add &dateStart= to the end of the URL.
If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
If the current URL contains ONLY ?dateStart= then replace it with the new one.
I have tried various methods to achieve this but I keep hitting the problem of appending information to the end of the URL rather than replacing parts of it.
Any help would be appreciated.
Thanks.
You can try something like this:
NOTE: not tested.
var newDateValue;
var myPath = window.location.pathname
//check if path contains the different variables
var containsFilter = myPath.indexOf("?filter=") != -1 ? true : false;
var containsAppendedDateStart = myPath.indexOf("&dateStart=" != -1 ? true : false;
var containsDateStart = myPath.indexOf("?dateStart=" != -1 ? true : false;
if(containsFilter && !containsAppendedDateStart){
// If the current URL contains ?filter= then add &dateStart= to the end of the URL.
window.location.replace(window.location.href + "&dateStart=");
}else if(containsFilter && containsAppendedDateStart){
//If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
newDateValue = 10; // add your new value here
var splittedPathArray = myPath.split("&dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "&dateStart=" + addNewValue;
window.location.replace(newUrl);
}else if(containsDateStart){
// If the current URL contains ONLY ?dateStart= then replace it with the new one.
newDateValue = 15;// add your new value here
var splittedPathArray = myPath.split("?dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "?dateStart=" + addNewValue;
}
You can achieve this more easy with native Web API or vanilla javascript than with jQuery. As far as jQuery don't provide any specific function to work with query strings.
The new URLSearchParams object provide a few methods to work more easily with URL query strings. In your case for example you'll need to do something like this:
function updateQueryString(queryString, dateStart) {
var queryString = new URLSearchParams(queryString);
queryString.has('dateStart')
? queryString.set('dateStart', dateStart)
: queryString.append('dateStart', dateStart);
return queryString.toString();
}
for this solution you'll need a polyfill
Sadly this is not yet implemented by the majority of web browsers and you'll need to "polyfill" the URLSearchParams object for this solution to work properly. You'll have to add this line to the <head> section in your html:
<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.14/polyfill.min.js"></script>
You can find more information about the URLSearchParams in the Mozilla Developers Network Documentation, the WHATWG specification for the URL Standard or the specification by the W3C
solution without polyfill
​
If you don't like to use edge features you still can do it without any extra polyfill. It would look like this:
function updateQueryString(queryString, dateStart) {
var qsObject = {};
queryString
.substring(1) // ignore '?'
.split('&').forEach(function (param) {
param = param.split('=');
qsObject[param[0]] = param[1];
});
qsObject['dateStart'] = dateStart;
return '&' + Object.keys(qsObject)
.map(function (key) {
return key + '=' + qsObject[key];
})
.join('?');
}
Call whatever version of the updateQueryString function you rather like this:
updateQueryString(windonw.location.search, dateStart)

regex detect url and prepend http:// [duplicate]

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.

how to check "contains" using jquery [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I tried of checking contains option using jquery for the birthday but its getting exception
var _dob = "4/10";
// this line doesn't work
var _adob = _dob.contains('/') ? _dob.Split('/') : _dob.Split('-');
$('#Month').val(_adob[0]);
$('#Day').val(_adob[1]);
but i can't able to split.. its resulting in error on getting _adob itself
Try this:
var _dob = "4/10";
var _adob;
if (_dob.indexOf("/") >-1) {
_adob = _dob.split("/");
} else {
_adob - _dob.split("-");
}
Direct Answer
indexOf(something)>-1
var _dob = "4/10";
var _adob = _dob.indexOf('/')>-1 ? _dob.split('/') : _dob.split('-');
$('#Month').val(_adob[0]);
$('#Day').val(_adob[1]);
Indirectly
You really don't need to check that the string contains that... Using a regular expression, you can split on a -, /, or . by building a character set:
var _dob = '4.10';
var _aodb = _dob.split(new RegExp('[-/.]'));

Categories

Resources