Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove tokenized string from URL and return

Code I’m implementing is trying to modify a URL by removing series of numbers and letters if available. What am I missing?

function removeToken() {
      let tokenUrl = "https://www.example.com/pathone/pathtwo/8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e/summary";
      let regex = new RegExp("/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*");// if url matches anything like 8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e
      if (regex.test(tokenUrl)) {
          tokenUrl = tokenUrl.replace("/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*", ''); //remove anything like /8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e from URL
          return tokenUrl; // desired return https://www.example.com/pathone/pathtwo/summary
      } else {
          return tokenUrl;
      }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Defining the regex directly without the class constructor works for me

function removeToken() {
let tokenUrl = "https://www.example.com/pathone/pathtwo/8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e/summary";
let regex = /\/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*/  // if url matches anything like 8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e
if (regex.test(tokenUrl)) {
    tokenUrl = tokenUrl.replace(regex, ''); //remove anything like /8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e from URL
    return tokenUrl; // desired return https://www.example.com/pathone/pathtwo/summary
} else {
    return tokenUrl;
}
}

You can also make it a bit more dry

function removeToken() {
    let tokenUrl = "https://www.example.com/pathone/pathtwo/8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e/summary";
    let regex = /\/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*/ 
    return tokenUrl.replace(regex, ''); 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading