skip to Main Content

I need to extract text but some parts are dynamic and change

This is my var

htts://query1.data.site.com/v7/finance/download/MYTEXT?period1=1664641287&period2=1696177287&interval=1d&events=history&includeAdjustedClose=true

I need to take only MYTEXT

These values changes

MYTEXT
1664641287
1696177287
1d

I tried with string.replace but I don’t know how to remove the dynamic parts

The solution I thought of was to remove all the text before and after MYTEXT but I can’t write a command that can do this

2

Answers


  1. Use a regexp that matches everything between the last / and ?

    const url = 'htts://query1.data.site.com/v7/finance/download/MYTEXT?period1=1664641287&period2=1696177287&interval=1d&events=history&includeAdjustedClose=true';
    const regexp = /[^/]+(?=?)/;
    match = url.match(regexp);
    console.log(match);
    Login or Signup to reply.
  2. Use URL to parse URL strings.

    You can get the pathname to extract MYTEXT, which will be the last segment separated by /‘s.

    You can get the searchParams to retrieve the value of specific query parameters like period1=1664641287

    const urlString = 'htts://query1.data.site.com/v7/finance/download/MYTEXT?period1=1664641287&period2=1696177287&interval=1d&events=history&includeAdjustedClose=true';
    
    const url = new URL(urlString);
    
    // You can get the last segment of the path like this 
    console.log(url.pathname.split('/').slice(-1)[0]);
    
    // You can also get query params like this if you need them
    console.log(url.searchParams.get('period1'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search