-1

I have a bug in my wysiwyg editor. I have a box where I past a tweet url, and I must extract the ID to replace it with the embed code.

regex: {
        twitter: /https?:\/\/twitter.com\/[a-zA-Z_]{1,20}\/status\/([0-9]*)/
    }

if (str.match(this.opts.regex.twitter)) {
  parsed = str.replace(this.opts.regex.twitter, '<blockquote class="twitter-tweet tw-align-center"><a href="https://twitter.com/x/status/$1">TWEET $1</a></blockquote>');
  return parsed;
   }

The bug is in my regex

 /https?:\/\/twitter.com\/[a-zA-Z_]{1,20}\/status\/([0-9]*)/

If I take this url

https://twitter.com/howard3141/status/1330546000969273347

It doesn't work because 'howard3141' has some numbers inside.

Roberto Pezzali
  • 2,484
  • 2
  • 27
  • 56
  • 1
    Please explain what constitutes a legal twitter username. Why not match anything up to the next slash? `[^/]+` instead of `[a-zA-Z_]{1,20}`. If you just want to handle numbers, add `\d`. – ggorlen Nov 25 '20 at 07:35
  • 2
    `/https?:\/\/twitter.com\/[0-9a-zA-Z_]{1,20}\/status\/([0-9]*)/` add digit to your username expression as `[0-9a-zA-Z_]`. – Heo Nov 25 '20 at 07:37
  • 1
    Why not use `location.pathName.match(/\/(.*)\//)[1]` – Rajesh Nov 25 '20 at 07:39

1 Answers1

0

Since you need to fetch from a URL, window.location provides great apis to get value.

Following is the demonstration of it.

Note: I'm using URL to create a location like object, but it should work with window.location as well

var url = new URL('', 'https://twitter.com/howard3141/status/1330546000969273347')

console.log(url.pathname.match(/\/([^\/]*)\//)[1])
Rajesh
  • 24,354
  • 5
  • 48
  • 79