NightTom
NightTom

Reputation: 485

Get substring from between two identical characters in a URL

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.

Upvotes: 0

Views: 328

Answers (1)

Multifarious
Multifarious

Reputation: 76

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/

Upvotes: 1

Related Questions