0

How can I use case switch with pathname and strip the guid that eventually gets attached to the URL?

here's what i've used:

*when the GUID comes in, i want to strip it from the URL and still use switch case to target the URL - the GUID. Are there any ways to do this?

var pushState = history.pushState;

function test(path) {
  switch (path) {
   case '/url here':
      //execute code
   break;
   case 'url here' +*GUID GETS ADDED HERE :
      //execute code
   break;
history.pushState = function() {
  pushState.apply(history, arguments);
 test(document.location.pathname);
};

2 Answers2

0

You need to use regular expressions (regex) to test for the presence of a GUID. Given a url https://www.example.com/be96b17b-0552-4d3a-8020-783d4430dd15, you build a regex

let guidRegex = /\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12}/

\w means to match characters a-z, A-Z, 0-9 and _ {x} means to match exactly this many characters, so 8 a-zA-Z0-9 characters followed by a hyphen followed by 4 a-zA-Z0-9 characters and so on. GUIDs follow a pattern of 8-4-4-4-12

To test for the presence of the guid in url you will use regex.test like guidRegex.test(url) which will return true or false. To extract the guid you will do use regex.exec like guidRegex.exec(url) which will return an array whose first element will be the extracted string.

You will probably have to evaluate the presence of the GUID outside of switch case and use that boolean value to determine which code block to execute.

Community
  • 1
  • 1
suv
  • 1,373
  • 1
  • 10
  • 18
0

try

switch (true) {
  case 'http://example.com' == path:
    console.log('url');
  break;
  case path.match("http://example.com/") && /[\w-]{36}/.test(path):
    console.log('url with guid');
  break;
}

var pushState = history.pushState;

function test(path) {

    switch (true) {
      case 'http://example.com' == path:
        console.log('url');
      break;
      case path.match("http://example.com/") && /[\w-]{36}/.test(path):
        console.log('url with guid');
      break;
    }

  // ...
};

test('abc');
test('http://example.com');
test('http://example.com/ca6834e0-d401-46fd-9421-f72b719e99ca');
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345