user63503
user63503

Reputation: 6493

how to replace part of the URL with JavaScript?

I have something like http://domain.com/Pages/SearchResults.aspx?function=search&selectedserver=intranet&search_query=MyRecords and need to replace it by JavaScript with something similar to http://domain.com/Pages/SearchResults.aspx?function=loginsearch&user=admin&password=admin&selectedserver=intranet&search_query=MyRecords — so

function=search 

is being replaced with

function=loginsearch&user=admin&password=admin

inside the URL. Need help with what JavaScript should I save as a button on a browser's tool bar to click and have the URL in the address bar replaced.

Upvotes: 22

Views: 126277

Answers (6)

Andriy Petrusha
Andriy Petrusha

Reputation: 129

My version. Works fine for me.

let url = window.location.toString();
window.history.pushState('', '', url.replace(searching_string, new_string));

Upvotes: 1

Franc
Franc

Reputation: 5494

The only way to update the displayed URL without reloading the page is history.pushState

window.history.pushState('', '', '/your-new-url');

Upvotes: 11

Black
Black

Reputation: 20352

var url             = window.location.href;               
window.location     = url.replace(/function=search/, 'function=loginsearch&user=admin&password=admin');

Upvotes: 0

Leonid
Leonid

Reputation: 712

You may find the dedicated library URI.js helpful, particularly setQuery() and addQuery() methods. I pasted this chunk of code directly into the console on that page and it seems to work:

var url = 'http://domain.com/Pages/SearchResults.aspx?function=search&selectedserver=intranet&search_query=MyRecords';
var uri = new URI(url);
var new_params = {'function': 'loginsearch', 'user': 'admin', 'password': 'admin'};
uri.setSearch(new_params);
console.log(uri.toString());

http://domain.com/Pages/SearchResults.aspx?function=loginsearch&selectedserver=intranet&search_query=MyRecords&user=admin&password=admin
<- undefined
>

It should be easy to turn this logic into a function (or a one-liner :)). As an aside, why are you passing the credentials right in the URL?

Upvotes: 0

Ruan Mendes
Ruan Mendes

Reputation: 92324

 location.href = location.href.replace(
    'function=search&', 'function=loginsearch&user=admin&password=admin&')

Upvotes: 5

Matt Ball
Matt Ball

Reputation: 360016

var url = window.location.toString();
window.location = url.replace(/function=search/, 'function=loginsearch&user=admin&password=admin');

Upvotes: 22

Related Questions