简体   繁体   中英

How do I remove part of a string from a specific character?

I have the following url:

http://intranet-something/IT/Pages/help.aspx?kb=1

I want to remove the ?kb=1 and assign http://intranet-something/IT/Pages/help.aspx to a new variable.

So far I've tried the following:

var link = "http://intranet-something/IT/Pages/help.aspx?kb=1"

if(link.includes('?kb=')){
  var splitLink = link.split('?');
}

However this just removes the question mark.

The 1 at the end of the url can change.

How do I remove everything from and including the question mark?

Use the URL interface to manipulate URLs:

 const link = "http://intranet-something/IT/Pages/help.aspx?kb=1"; const url = new URL(link); url.search = ''; console.log(url.toString());

 var link = "http://intranet-something/IT/Pages/help.aspx?kb=1" if (link.includes('?kb=')) { var splitLink = link.split('?'); } var url = splitLink? splitLink[0]: link; console.log(url);

 var link = "http://intranet-something/IT/Pages/help.aspx?kb=1" if(link.includes('?kb=')){ var splitLink = link.split('?'); console.log(splitLink[0]); }

You can also try like this

 const link = "http://intranet-something/IT/Pages/help.aspx?kb=1"; const NewLink = link.split('?'); console.log(NewLink[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM