Fix QR Code Bug When Short URL Contains a Dot in jQuery

Referencing 233boy's QR code tool. https://233boy.github.io/tools/qr.html

The QR code JS used is

https://cdn.jsdelivr.net/gh/lrsjng/jquery-qrcode@0.18.0/dist/jquery-qrcode.min.js

and depends on jQuery

https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js


Modify index.html.

Add a "Generate QRcode" button after the existing short URL text field.

LocalStorage List interface showing short link list with QR button highlighted

Then, between the existing short URL row and the long URL row, add a div as a placeholder for the QR code.

LocalStorage List interface showing short link list with load localStorage, clear localStorage, and QR buttons

When the button is pressed, it generates the QR code and fills it into that placeholder div.


Found something interesting during debugging.

The interesting thing is, if the short URL itself contains a dot . , for example

Free Cloudflare Worker and KV URL shortener page showing the Shorten it button

the QR code cannot be generated.

Looking at the code, the statement for generating the QR code is written using jQuery syntax.

$("#qrcode-" + shortUrl ).empty().qrcode(options);  

And in jQuery's select syntax, the dot . has special meaning.

So I asked GPT again https://devv.ai/search?threadId=dht5vhmnhh4w

jQuery answer showing escapeSelector escaping an element with a dot and calling fillSelect

The replace in it is the code to copy.

Changed it to this and it works properly.

$("#qrcode-" + shortUrl.replace(/(:|\.|\[|\]|,|=|@)/g, "\\$1") ).empty().qrcode(options);


========

Github

https://github.com/crazypeace/Url-Shorten-Worker

Demo site

https://urlsrv.crazypeace.workers.dev/bodongshouqulveweifengci

Comments