1

Having a string of the below structure how can i extract only the link portion of it. https://qr.1688.com/s/OaPpTrzR CZ0736

https://qr.1688.com/s/2Q8NXya1 CZ3050

const getShortUrl = (string)  =>{
    let query = string.trim().replaceAll('"', '');
    if(query.indexOf('https://qr') >= 0){
          return query.substring(query.indexOf('https://qr'));
        
    }
  }


But the above code return something like `https://qr.1688.com/s/2Q8NXya1 CZ3050` but what i wanted is something like this `https://qr.1688.com/s/2Q8NXya1`

how can i extrract this portion of string.
sam
  • 853
  • 3
  • 19
  • 50
  • Does this answer your question? [Extracting for URL from string using regex](https://stackoverflow.com/questions/31760030/extracting-for-url-from-string-using-regex) – tevemadar Mar 04 '23 at 13:18
  • Or https://stackoverflow.com/questions/33211233/how-to-detect-and-get-url-on-string-javascript – tevemadar Mar 04 '23 at 13:18

2 Answers2

3

You can split the string into parts by the space with the .split(" ") method. And then just use the first element of the created array.

Example

query = query.split(" ")[0]

With your code

const getShortUrl = (string) => {
  let query = string.trim().replaceAll('"', '');
  query = query.split(" ")[0]
  if (query.indexOf('https://qr') >= 0) {
    return query.substring(query.indexOf('https://qr'));

  }
}

const shortUrl = getShortUrl("https://qr.1688.com/s/OaPpTrzR CZ0736")
console.log(shortUrl)
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
2

You can use split:

return query.split(' ')?.[0];
dom1
  • 425
  • 1
  • 2
  • 19