JavaScript Substring From String With Variable Contents

- 1 answer

I have a string that can contain various bits of information, I need to substring a GUID from this when I cant be certain of the position of the GUID within the string.

Possible versions of the string

stringVar=email:[email protected]&room:b83edd0d-fec5-4ec0-8055-60bc0d8eb4b6;

stringVar=email:[email protected]&room:b83edd0d-fec5-4ec0-8055-60bc0d8eb4b6&host=HOSTNAME;

stringVar=email:[email protected]&location=SomeCity&room:b83edd0d-fec5-4ec0-8055-60bc0d8eb4b6;

There are a few other permutations of the string with more or less fields, it will always at least contain the GUID.

A rough version of what I have:

var room = str.substring(str.lastIndex(room),str.lastIndex(;))
if room.length !== 36
    var room = str.substring(str.lastIndex(room),str.lastIndexOf(&)

There must be a cleaner way to do this?



There must be a cleaner way to do this?

There is - REGEX.

var guid = str.match(/room:([^&]+)/);

The match, if found, will then live in guid[0], with the guid alone (minus "room:") in guid[1].