Search code examples
javascripturlcharacterdetectionipfs

Advanced checking of URL content (characters count, * operator)


I'm building FrameworkJS, and one of its usage is to detect its environment.

Recently, I've added these 3 conditions to detect if URL contains the desired text:

if(window.location.href.indexOf("ba"*".ipfs.") > -1) {
       alert("Alert: IPFS!");
}

if(window.location.href.indexOf("/ipfs/Qm") > -1) {
       alert("Alert: IPFS!");
}

if(window.location.href.indexOf("/ipfs/ba") > -1) {
       alert("Alert: IPFS!");
}

It displays an alert when the IPFS environment is detected.

Only the last two have worked:

https://ipfs.io/ipfs/Qmc92ioRvt1KB18GanLUq8qMrXoTeaj4m9iXX3NmjaYWTN/

https://ipfs.io/ipfs/bafybeignbgeutsyhunhidcki63wmvmjfib7xipmiorwlt3o27aot2ydgwu/#x-ipfs-companion-no-redirect

But the first haven't worked:

https://bafybeignbgeutsyhunhidcki63wmvmjfib7xipmiorwlt3o27aot2ydgwu.ipfs.dweb.link/#x-ipfs-companion-no-redirect

if(window.location.href.indexOf("ba"*".ipfs.") > -1) {
       alert("Alert: IPFS!");
}

How to check if an URL contains "ba" and everything (* operator that works on Shell/Bash) between "ba" and ".ipfs."? What operator and syntax adjustment to use?

Also, an bonus: how to include on this detection, and count/validate how many characters this starting "ba" haves after the protocol (https://) and .ipfs., like here "https://bafybeignbgeutsyhunhidcki63wmvmjfib7xipmiorwlt3o27aot2ydgwu.ipfs." that is "bafybeignbgeutsyhunhidcki63wmvmjfib7xipmiorwlt3o27aot2ydgwu" (should be 59 characters)?


Solution

  • Have you heard of regular expressions (regex)?

    In your case, you could try matching the URL against /ba(.*)\.ipfs\./

    So your code would look something like:

    if(window.location.href.match(/ba(.*)\.ipfs\./)) {
           alert("Alert: IPFS!");
    }
    

    Feel free to test here: https://regex101.com/

    You can learn more about regex in Javascript here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions