2

Is there some better/official way, how to compare CRM 2011 GUIDs in JavaScript

2e9565c4-fc5b-e211-993c-000c29208ee5=={2E9565C4-FC5B-E211-993C-000C29208EE5}

without using .replace() and .toLowerCase()?

First one is got thru XMLHttpRequest/JSON:

JSON.parse(r.responseText).d.results[0].id 

Second one is got from form:

Xrm.Page.getAttribute("field").getValue()[0].id
jcjr
  • 1,503
  • 24
  • 40

3 Answers3

3

There is no official way to compare GUIDs in JavaScript because there is no primitive GUID type. Thus you should treat GUIDs as strings.

If you must not use replace() and toLowerCase() you can use a regular expression:

// "i" is for ignore case
var regExp = new RegExp("2e9565c4-fc5b-e211-993c-000c29208ee5", "i"); 

alert(regExp.test("{2E9565C4-FC5B-E211-993C-000C29208EE5}"));

It would probably be slower than replace/toLowerCase().

Atanas Korchev
  • 30,562
  • 8
  • 59
  • 93
  • replace() and toLowerCase() are not forbidden, but it didn't appeared to me right; I would expect MS provides some method in SDK, when CRM returns the same GUID in two different forms. Your solution with regex seems to me like a little bit more clear code. – jcjr Feb 21 '13 at 12:56
2
var rgx = /[\{\-\}]/g;
function _guidsAreEqual(left, right) {
    var txtLeft = left.replace(rgx, '').toUpperCase();
    var txtRight = right.replace(rgx, '').toUpperCase();
    return txtLeft === txtRight;
};
user1920925
  • 672
  • 6
  • 5
  • The functions removes separators and performs case insensitive comparison after that. Regex may be placed inside function's body. – user1920925 Nov 04 '15 at 19:09
1

You can use the node-uuid (https://github.com/broofa/node-uuid) library and do a byte comparison after parsing the strings into bytes. The bytes are returned as arrays and can be compared using the lodash _.difference method. This will handle cases where the GUID's aren't using the same case or if they don't have '-' dashes.

Coffeescript:

compareGuids: (guid1, guid2) ->
    bytes1 = uuid.parse(guid1)
    bytes2 = uuid.parse(guid2)
    # difference returns [] for equal arrays
    difference = _.difference(bytes1, bytes2)
    return difference.length == 0

Javascript (update):

compareGuids: function(guid1, guid2) {
    var bytes1, bytes2, difference;
    bytes1 = uuid.parse(guid1);
    bytes2 = uuid.parse(guid2);
    difference = _.difference(bytes1, bytes2);
    return difference.length === 0;
  }
Stone
  • 2,608
  • 26
  • 26
  • 1
    I would prefer the code sample in JS and information to download the other library, but I made it working and it works fine. It seems complicated for a quick use on a CRM form, but can be neat for large projects. Thanks! – jcjr Dec 08 '14 at 08:12