Home > front end >  Removing a part of an URL in Javascript
Removing a part of an URL in Javascript

Time:01-20

Suppose there's this url: https://www.google.com/search?q=test&hl=en&sxsrf=AOaemvLX0o7... And I want the site to refresh with the same URL but removing the part after and including &. For instance: https://www.google.com/search?q=test.

I'm doing a bookmarklet on Chrome for this and get that you have to use regular expression for this and I did something like this:

`javascript: (() => {  window.location.href = window.location.replace(/\& /i,''); })();`

but to no avail.

CodePudding user response:

const url = "https://www.google.com/search?q=test&hl=en&sxsrf=AOaemvLX0o7"
const [replacedUrl] = url.split('&')
console.log(replacedUrl)

CodePudding user response:

To remove everything from the first & use this regex expression instead

replace(/&.*$/,'')

CodePudding user response:

Search for the first ampersand, then remove it along with anything that follows:

let url = "https://www.google.com/search?q=test&hl=en&sxsrf=AOaemvLX0o7...";
let strippedUrl = url.replace(/\&.*$/, "");
console.log(strippedUrl);

Explanation

  • \& matches an ampersand
  • .* matches any character between zero and infinite times
  • $ asserts that the expression matches until the end of the input string

CodePudding user response:

You can just split the url using Ampersand as divider:

javascript: (() => {document.location.href = document.location.href.split("&")[0];})();

or

javascript: (() => {window.location.href = window.location.href.split("&")[0];})();
  •  Tags:  
  • Related