Home > Mobile >  Javascript: GUID: RegEx: string to GUID
Javascript: GUID: RegEx: string to GUID

Time:11-24

I have a textbox that a user can paste into using Ctrl V. I would like to restrict the textbox to accept just GUIDs. I tried to write a small function that would format an input string to a GUID based on RegEx, but I can't seem to be able to do it. I tried following the below post: Javascript string to Guid

function stringToGUID()
{
    var strInput = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
    var strOutput = strInput.replace(/([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/,"$1-$2-$3-$4-$5");
    console.log(strOutput );
    //from my understanding, the input string could be any sequence of 0-9 or a-f of any length and a valid giud patterened string would be the result in the above code. This doesn't seem to be the case;
    //I would like to extract first 32 characters; how do I do that?

}

CodePudding user response:

I suggest that you remove the dashes, truncate to 32 characters, and then test if the remaining characters are valid before inserting the dashes:

function stringToGUID()
{
    var input = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
    let g = input.replace("-", "");
    g = g.substring(0, 32);
    if (/^[0-9A-F]{32}$/i.test(g)) {
        g = g.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
    }
    console.log(g);
}

stringToGUID();

(The i at the end of the regex makes it case-insensitive.)

CodePudding user response:

You are already matching 32 characters with the pattern, so there is no need to get a separate operation to get 32 characters to test against.

You can replace all the hyphens with an empty string, and then match the pattern from the start of the string using ^

Then first check if there is a match, and if there is do the replacement with the 5 groups and hyphens in between. If there is not match, return the original string.

The function stringToGUID() by itself does not do anything except log a string that is hardcoded in the function. To extend its functionality, you can pass a parameter.

function stringToGUID(s) {
  const regex = /^([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/;
  const m = s.replace(/- /g, '').match(regex);
  return m ? `${m[1]}-${m[2]}-${m[3]}-${m[4]}-${m[5]}` : s;
}

[
  'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
  'b6b954d9-cbac-4b18-b0d5-a0f725695f1c',
  '----54d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
  '!@#$%'
].forEach(s => {
  console.log(stringToGUID(s));
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related