i have an url like this
/users/?i=0&p=90
how can i remove in js the part from
? to 90
can any one show me some code?
EDIT
i mean doing this with window.location.href (so in browser url bar directly)
i tryed
function removeParamsFromBrowserURL(){
document.location.href = transform(document.location.href.split("?")[0]);
return document.location.href;
}
also i would like to not make redirect, so just clean the url from ? to end
function removeParamsFromBrowserURL(){
return window.location.href.replace(/\?.*/,'');
}
If you only want the /users/ portion:
var newLoc = location.href.replace( /\?.+$/, '' );
You could also split the string, and return the first portion:
var newLoc = location.href.split("?")[0];
Or you could match everything up to the question mark:
if ( matches = location.href.match( /^(.+)\?/ ) ) {
alert( matches[1] );
}
One way is leftside = whole.split('?')[0], assuming there's no ? in the desired left side
http://jsfiddle.net/wjG5U/1/
This will remove ?... from the url and automatically reload the browser to the stripped url (can't get it to work in JSFiddle) I have the code below in a file, and put some ?a=b content manually then clicked the button.
<html>
<head>
<script type="text/javascript">
function strip() {
whole=document.location.href;
leftside = whole.split('?')[0];
document.location.href=leftside;
}
</script>
</head>
<body>
<button onclick="strip()">Click</button>
</body>
</html>
If you only want the /users/ portion, then you could just substring it:
var url = users/?i=0&p=90;
var urlWithNoParams = url.substring(0, url.indexOf('?') - 1);
That extracts the string from index 0 to the character just before the '?' character.
I had problems with #page back and forth referrals sticking in the url no matter which url redirect I used. This solved everything.
I used the script like this:
<script type="text/javascript">
function strip() {
whole=document.location.href;
leftside = whole.split('#')[0];
document.location.href=leftside;
}
</script>
<a onclick="strip()" href="http://[mysite]/hent.asp" >Click here</a>
Related
(1)
My example Current URL along with Parameters is ----
www.example.com?fname=John&femail=john123#example.com
(2)
Through html / JavaScript
I want to check Current URL Parameter whether it contains any data in
fname
(3a)
Next, If there is No URL Parameter present then Redirect to "www.example.com/error-page"
or
(3b)
If the parameter fname have some data (No need for any Validation of data) meaning the parameter fname is not empty then should Continue with the execution of Current Page.
I tried the following successfully :
<!doctype html>
<html>
<head>
<body>
<div>
<p id ="dd"></p>
</div>
<meta charset="UTF-8"/>
<script type="text/javascript">
var iid=document.getElementById("dd");
var getURL=window.location.href;
var theString = window.location.href;
var theWord = "fname";
var theWordExp = /fname/g;
if (theString.search(theWordExp) == -1) { window.location.href=
('www.example.com/error-page'); };
</script>
</body>
</head>
</html>
Explanation:
"I want to check Current URL Parameter whether it contains any data in fname"
The getQueryParam function is explained here
How to get "GET" request parameters in JavaScript?
basically it's almost the same as your approach using the location href to parse the params
"If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)
Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method
const getQueryParam = (name) => {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
let fnameParam = getQueryParam("fname");
if (!fnameParam) {
window.location = "http://www.example.com/error-page";
};
<!doctype html>
<html>
<head>
<body>
<div>
<p id="dd"></p>
</div>
</body>
</head>
</html>
On my site mysite.com I load scripts from anothersite.com. Is there a way for a script running on mysite.com to know that it was downloaded from anothersite.com?
I found this to the the solution:
function serverName() {
var server = "";
//IE and EDGE can't use the case-insensitive 'i' in this selector
var path = $('script[src*="loader.js"]').attr('src'); //Look for the script tag of this script and get the URL
var regex = RegExp('.*\/\/.*?\/'); // gets this: http://mysite/
var m = regex.exec(path);
if (m && m.length) {
server = m[0].replace(/\/$/, "");//trim trailing slash
}
return server;
}
<!doctype HTML>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js" id="know"></script>
</head>
<body>
Hello
<script>
const gebi=id=>document.getElementById(id)
console.log(gebi('know').src)
</script>
</body>
</html>
This would work
const domain = location.hostname;
See more about location.hostname
The hostname property sets or returns the hostname of a URL.
Hello I am super new to building websites. Please excuse my lacking terminology!!
I have a website that has Wildcard sub-domains. It is using this script to pull the wildcard sub-domains usernames.
<p id="dist-info"></p>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
return;
var get_data_url = 'https://backoffice.WEBSITE.com/api/v2/public/users/{username}';
$.getJSON(get_data_url, function( data ) {
var dist_info = "<p>"+data.response['first-name']+"</p>" +
"<p>"+data.response['last-name']+"</p>" +
"<p>"+data.response['distributor-id']+" "+data.response.email+"</p>" +
"<p>"+data.response['image-url']+"</p>" +
"<p>Phone: "+data.response.phone+"</p>";
$('#dist-info').html(dist_info);
});
});
</script>
Now I need to make a URL that will parse the username/user id out of the Wildcard Subdomain page. What code do I need to use?
For example
The URL is
USERNAME.WEBSITE.com/page/subpage/
I need to make this URL
backoffice.WEBSITE.com/page?sponsor-id=USERNAME
What do I need to do so that the username from the first page is parsed out and applied to the link of the second URL
You want to modify this JavaScript so it uses the subdomain instead of {username}?
$(document).ready(function() {
var get_data_url = 'https://backoffice.WEBSITE.com/api/v2/public/users/';
var hostname_parts = location.hostname.split('.');
var username = hostname_parts.shift();
// add username to the data URL
get_data_url += username;
// add username to some link on the website
var $aTag = $('#id-of-the-link');
var link_url = $aTag.attr('href');
link_url += username;
// set the new href attribute
$aTag.attr('href', link_url);
location.hostname gives you USERNAME.WEBSITE.com, split() splits it into parts separated by a dot. shift() takes the 1st element of this array (you could also use hostname_parts[0]) and with += you concatenate it to the URL.
The second example shows how to add the username at the end of a link like
click
Edit: added example for changing a href attribute
What I am trying to achieve is if a particular page is loaded in the browser for e.g www.domain.com/page then the following piece of code should be added in the page dynamically using JS (similar to how we load the Google Analytics code)
<div id="something">
<img src="http://domain.com/images/someImage.jpg">
</div>
I am trying to figure the script which will load the above mentioned HTML code (anywhere of the page - www.domain.com/page)
Edit 1:
what I am trying to achieve is when the user goes to www.domain.com/page.html I am calling another page lets say page1.html which should contain the script which insert the HTML code I posted above. So I simply want to insert the function which should be enclosed in the tag inside page1.html. Unfortunately I can not edit www.domain.com/page.html
If you want to PLACE that code anywhere in your page using javascript, you first need to identify that PLACE in DOM Using an "id" attribute. Here's an example:
HTML:
<html>
<body>
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>
JS:
var html = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
document.getElementById('target1').innerHTML = html;
document.getElementById('target2').innerHTML = html;
You can try something like this :
$(document).ready(function () {
var url = window.location.href;
$("#something").append("<img src='"+ url +"' />");
});
$(".documentholder").load("code.html");
If you a specific id of something
$(".documentholder").load("code.html #someid");
If you a specific tag and id of something
$(".documentholder").load("code.html #someid");
Here you are,
just change this part if (getFileName() == "js") with if (getFileName() == "page")
I added js because that is what is returning in the code snippet :)
function getFileName() {
var url = document.location.href;
url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
url = url.substring(url.lastIndexOf("/") + 1, url.length);
return url;
}
var div = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
if (getFileName() == "js") {
$('body').append(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
let's say you save this code in a html-file named something.html
$(".documentholder").load("something.html");
in this case the class "documentholder" is the container you put the code in
I'm new in Jquery, I would like to have Jquery code to get the current page url and if the url contains certain string then load remote element.
example:
i have the page urls like this:
"http://......./Country/AU/result-search-to-buy"
"http://......./Country/CA/result-search-to-buy"
"http://......./Country/UK/result-search-to-buy"
the part "/Country/AU" is what I need to determine which page element I should load in, then if "AU" I load from "/state-loader.html .state-AU", if "CA" I load from "/state-loader.html .state-CA"
I have a builtin module "{module_pageaddress}" to get the value of the current page url, I just dont know the Jquery logic to let it work.
I expect something like this:
if {module_pageaddress} contains "/Country/AU/"
$('#MyDiv').load('state-loader.html .state-AU');
if {module_pageaddress} contains "/Country/CA/"
$('#MyDiv').load('state-loader.html .state-CA');
please help and many thanks.
Here is some code:
<!DOCTYPE html>
<html>
<head>
<title>jQuery test page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
function stateURL() {
var startOfResult = '../../state-loader.html #state-';
var match = (/(?:\/Country\/)(AU|US|CA|UK)(?:\/)/).exec(window.location.pathname);
if (match) {
return startOfResult + match[1];
} else {
return startOfResult + 'AU';
}
}
</script>
</head>
<body>
Link 1
<div id="content">content will be loaded here</div>
</body>
</html>
And the file to load the different content for the states:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="state-US">Go USA!</div>
<div id="state-CA">Go Canada!</div>
<div id="state-AU">Go Australia!</div>
<div id="state-UK">Go United Kingdom!</div>
</body>
</html>
See it work here:
http://www.quirkscode.com/flat/forumPosts/loadElementContents/Country/US/loadElementContents.html
Replace .../US/... with .../AU/..., etc. to see how it behaves.
Original post where I got the ideas/original code:
http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html
You can try
var countryCode = ... // parse the country code from your module
$('#yourDiv').load('state-loader.html .state-' + countryCode);
See more examples of .load() here.
As far as pulling the url path you can do the following
var path_raw = document.location.path,
path_array = path_raw.split("/");
Then, you could do something like this:
$.ajax({
url: "./remote_data.php?country=" + path_array[0] + "&state=" + path_array[1],
type: "GET",
dataType: "JSON",
cache: false,
success: function(data){
// update all your elements on the page with the data you just grabbed
}
});
Use my one line javascript function for getting an array of the URL segments: http://joshkoberstein.com/blog/2012/09/get-url-segments-with-javascript
Then, define the variable $countrySegment to be the segment number that the country code is in.
For example:
/segment1/segment2/CA/
(country code would be segment 3)
Then, check if the 3rd array index is set and if said index is either 'CA' or 'AU'. If so, proceed with the load, substituting in the country-code segment into the .html filename
function getSegments(){
return location.pathname.split('/').filter(function(e){return e});
}
//set what segment the country code is in
$countrySegment = 3;
//get the segments
$segments = getSegments();
//check if segment is set
//and if segment is either 'AU' or 'CA'
if(typeof $segments[$countrySegment-1] !==undefined && ($segments[$countrySegment-1] == 'AU' || $segments[$countrySegment-1] == 'CA')){
$countryCode = $segments[$countrySegment-1];
$('#target').load('state-loader.html .state-' + $countryCode);
}
var result= window.location.pathname.match(/\/Country\/([A-Z]+)\//);
if(result){
$('#MyDiv').load('state-loader.html .state-' + result[1]);
}