Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace part of the URL with JavaScript?

Tags:

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.

like image 271
user63503 Avatar asked Jan 12 '11 01:01

user63503


People also ask

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

How do I replace and in a URL?

You should use '&amp;' instead found in php-style links (i.e. < a href="index.

How do you substitute in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

Can you modify a string in JavaScript?

Javascript strings are immutable, they cannot be modified "in place" so you cannot modify a single character. in fact every occurence of the same string is ONE object.


2 Answers

var url = window.location.toString();
window.location = url.replace(/function=search/, 'function=loginsearch&user=admin&password=admin');
like image 136
Matt Ball Avatar answered Oct 09 '22 12:10

Matt Ball


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

window.history.pushState('', '', '/your-new-url');
like image 41
tocqueville Avatar answered Oct 09 '22 11:10

tocqueville