ian.blair@softstuff

My technical musings

Compare Guids in JavaScript

One of the problems with Guids in JavaScript is they can come in a few different formats depending on where you get them from, and as JavaScript doesn’t have a dedicated Guid data type like other languages such as C# it can make comparing them tricky. 

Examples of the same Guid are:

9D6FF5B4-C4C2-E511-8108-1458D043F638

{9D6FF5B4-C4C2-E511-8108-1458D043F638}

9d6ff5b4-c4c2-e511-8108-1458d043f638

{9d6ff5b4-c4c2-e511-8108-1458d043f638}

Some will have {} some will be in uppercase, and some in lower which makes doing a comparison between them tricky, especially as you are effectively doing a simple text comparison.

Usign a little regex a simple function like this can be used.

function CompareGuid(guid1,guid2){
  If(guid1.replace(/[{}]/g,””).toLowerCase()==guid2.replace(/[{}]/g,””).toLowerCase())
     return true;
  }
  return false;
}

 

The functions takes two Guids and performs a text comparison between them, but first it removes the {} and converts them to lower case before comparing.