Fetch current URL, replace part of pathname, and open in blank tab - javascript

I 'd like to grab the current URL, replace a part of the pathname within it, and open the result in a new tab.
The current URL looks something like this:
http://website.com/file.php?identificator=11111&folder=name
I would like to get the URL (I assume using "window.location" to be most suitable (?)), then replace the parameter "name" (variable, could be different at any time) with "name2" (fixed value) and open resultant URL in a new tab, possibly multiple times.
I've tried looking into replace(), but couldn't get into isolating the parameter inside the pathname.
How would one proceed? jQuery could be a possible replacement too.
Thanks for any help.

<script>
url = window.location.href;
newurl = url.replace(url,"http://website.com/file.php?identificator=11111&folder=anything
"); // your replacement
window.onload = window.open(newurl);
</script>
*untested code

Related

C#/Razor replace second question mark with ampersand in query string

I am using C# and I have a CMS that uses an open text field. I am doing a redirect manually appending a query string BUT on top of that, I have editors putting UTMs into the URL. I am trying to track the redirects/vanity URLs so we an see the success of them, but the editors are adding UTMs and when I am transferring the redirect, I prepend "?ref=" to their URL to the second URL.
I need to know how to replace any subsequent question marks in the query string.
The CMS is seeing the second question mark and automatically redirecting to the homepage, because I think it is trying to be smart with the URL and the second question mark is causing it to think the URL is invalid.
So the original URL I am getting looks something like this:
www.mysite.com/somepage?utm_source=foo&utm_medium=bar
BUT it then redirects so I can track the URL and it looks now like this
www.myothersite.com/this-other-page?ref=www.mysite.com/somepage?utm_source=foo&utm_medium=bar
So what I want to do is in the second URL is to replace the second question mark with an ampersand. How would I do only the second or subsequent ones without getting rid of the first one?
I am using Javascript to do the redirect in the view.
My code so far
#{
var currentPageUrl = HttpContext.Current.Request.Url.AbsoluteUri;
}
<script type="text/javascript">
setTimeout(function () {
window.location.href = '#Model.Content.GetPropertyValue("externalRedirectURL")?ref=#currentPageUrl';
}, 200); //will call the function after 2 secs
</script>
I found my answer now using HTML.Raw and Json.Ecode.
When I did generic .Replace in the actual Javascript built string, for some reason the .Replace("?", "&") was adding another ampersand to anything in the query string with an ampersand already in the query string. Not what I expected.
Anyways, here is my answer
<script>
var currentP = #Html.Raw(Json.Encode(#currentPageUrl.Replace("?","&")));
setTimeout(function () {
window.location.href = '#Model.Content.GetPropertyValue("externalRedirectURL")' + '?ref=' + currentP;
}, 200); //will call the function after 2 secs
</script>

Problem Splitting Code at '%2F', not at '/'

So, I'm working on a bookmarklet that takes the website url, which contains the actual text '%2F' in it, and split it there. However, because %2F represents a forward slash, it keeps splitting where there are forward slashes and not at %2F. How can I fix this?
Current Code:
javascript:(
function(){
var str = window.location.href;
var res = str.split("%2F");
alert(res); //Just here to test the output
}
)
();
Example Input:
http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg
Example Output:
http:,,blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg
Wanted Output:
http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com ,4uHAdNPg.jpg
It looks like you want you focus your splitting more to a specific portion of the location rather that the whole URL. In your case, it looks like you really want to split the value of the url variable which is found in window.location.search. You can probably accomplish close what you want if you just use that instead of window.location.href.
A better approach might be to target the actual value of the url variable.If you don't need to support IE, an easy way to get that data is to use UrlSearchParams:
const params = new URLSearchParams(window.location.search);
const url = params.get("url");
const res = url.split('%2F');
If you do need more cross browser reach, you can also do this with a simple regular expression:
const url = window.location.search.match(/url=[^&]+/)
const res = url.split('%2F');
The split works as expected:
const str = 'http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg';
console.log(str.split('%2F'));
But window.location.href doesn't always return exactly the same string that is being displayed in the address bar, or encode stuff without you knowing about it. It is quite browser-dependent. For example, on chrome, you might observe this:
location.href = 'http://example.com/ xxx';
console.log(location.href); // http://example.com/%20xxx
In any case, it just looks like you're trying to manipulate your URL by hand. Don't do that. By using new URL(...), location.searchParams, decodeURIComponent, and other native APIs to easily manipulate URLs, you'll probably achieve what you're looking for in an easier and safer way ;)

Get uri parameter with javascript than return it to new url?

im not that familir with javascript but i need some help . Basically i have this scenario : i want to get a parameter from url , lets say http://mysite1.com/path/#me=VALUE_OF_ME_PARAMETER here also i have a javascript code which redirects to a second site , lets say mysite2.com/path1 , so what i need is when mysite1 redirects to mysite2 i want it also to return http://mysite2.com/path1/#me=VALUE_OF_ME_PARAMETER , where #me parameter value is the same.
If you wish to reuse the complete "hash" part of the Location (the part after and including #...), you can say:
window.location = "http://mysite2.com/path1/" + window.location.hash;
This will also redirect you to http://mysite2.com/path1/#me=VALUE_OF_ME_PARAMETER, if executed from http://mysite1.com/path/#me=VALUE_OF_ME_PARAMETER.
Check the following code: First you must get the url via window.location.href method. Then I make a function using regex obj with two arguments. First the url string and second the name of the url parameter that i want to get.
var url_string = "http://localhost:9080/l?state=12345&code=my_code_here";
function getValueUrl(url,name){
var a=new RegExp(name+'=([^&]+)');
a=a.exec(url)[1];
return a;
}
console.log(getValueUrl(url_string, 'code'));

Embedding JavaScript objects in a page's URL

I'm trying to store a JavaScript object in the URL of a web page (as a JSON string), but the URL contains some characters that will not work with HTML links.
On this page, a JavaScript object is loaded from the page's URL:
http://jsfiddle.net/tsUpC/1/show/#["Hello","World!"]
and on this page, I'm trying to create a link to the same page that is shown above, but the URL contains characters that are not allowed in hyperlinks:
http://jsfiddle.net/M6dRb/
This link doesn't work because the URL contains characters that are not allowed in HTML links.
Is it possible to embed JavaScript objects into URLs without using characters that are not compatible with hyperlinks?
You can put a JSON string in an URL by URL-encoding it before putting it in the URL:
encodeURIComponent(JSON.stringify(object))
In your example, that would be:
http://jsfiddle.net/tsUpC/1/show/#%5B%22Hello%22%2C%22World!%22%5D
As you might guess, the opposite of encodeURIComponent is decodeURIComponent.
You need to encode and decode with JSON
var link = document.getElementsByTagName('a')[0];
link.addEventListener('click', function(){
// this could also be done with location.hash = JSON.stringify(...);
var param = JSON.stringify(['your', 'array']),
href = '#'+this.getAttribute('href');
href += param;
location.href = href;
}, false);
// make string an object/array again
var obj = JSON.parse(window.location.hash.substr(1));

Appending query strings from multiple pages

I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.

Categories

Resources