haddow64 haddow64 - 2 months ago 8
Javascript Question

JavaScript substring from string with variable contents

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




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].