0

How would I extract just the number from between the two slashes in this URL:

https://myDomain.sharepoint.com/sites/MySite/SitePages/MyPage.aspx?/id=612/&CT=1223336827303&OR=OWA-NT&CID=7f71df69-6cef-fd22-82d9-5823a32895f9

I only want the number (612 in this case but can be different no. and can vary in length) and nothing else.

The code I've attempted:

    if(window.location.href.indexOf("id=") > -1){
      var url = window.location.href;
      console.log(url, 'url');
      var findUrl = window.location.search;
      console.log(findUrl, 'findUrl');
       var url2 = url.substring(url.indexOf("=") + 1);
      console.log(url2, 'url2');

      var url3 = url.substring(
        url.lastIndexOf("/") + 1,
        url.lastIndexOf("/")
      );

      var url4 = url.split('/').pop().split('/')[0];

      console.log(url3, 'url3');
      console.log(url4, 'url4');
      
      this.setState({
        Id: url4,
        filterValue: url4
 
      },  () => {
        
       this._editItemUrl();
      });
     
    }

I've read: How do you use a variable in a regular expression? JavaScript - Use variable in string match get string between two strings with javascript

Buy none answer my specific question.

NightTom
  • 418
  • 15
  • 37

1 Answers1

1

your problem is the forward slashes in the query-parameter string. If you can remove those (str replace) you can use JS's URLSearchParams.

see: https://www.sitepoint.com/get-url-parameters-with-javascript/

Multifarious
  • 76
  • 1
  • 4
  • Can you provide an example of how to remove the two slashes please. I've tried creating the url without the slashes and the link destination doesn't work without them, but if they could be removed when the page is hit, that might work. Please provide an example. – NightTom Jun 10 '21 at 15:52
  • 1
    something like this should work: const queryString = window.location.search.replaceAll('/',''); console.log(queryString); – Multifarious Jun 10 '21 at 15:56
  • I get back ```?id=611``` so could I then use URLSearchParams? Provide an example? – NightTom Jun 10 '21 at 16:00
  • see the page I linked for more info.. the "replaceAll()" function is the only thing you need to add – Multifarious Jun 10 '21 at 16:01
  • I had to use: ```let queryString2 = queryString.replace('?id=',''); console.log(queryString2, 'queryString2'); const queryString3 = queryString2 = queryString2.split('&')[0];``` to remove everything from the end – NightTom Jun 10 '21 at 16:26
  • Not sure that's helpful in the slightest. I did look at the link but it wasn't useful. What WAS useful were your comments under your answer. Which is why I accepted your answer. It's unfortunate that you have to respond in such a way. – NightTom Jun 11 '21 at 10:43
  • "wasn't useful": var queryString = window.location.search.replaceAll('/',''); var params = new URLSearchParams(queryString); console.log(params.get('id')); My only addition is the replaceAll – Multifarious Jun 11 '21 at 11:53