haddow64 haddow64 - 1 month ago 6
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


stringVar=email:name@company.com&room:b83edd0d-fec5-4ec0-8055-60bc0d8eb4b6;

stringVar=email:name@company.com&room:b83edd0d-fec5-4ec0-8055-60bc0d8eb4b6&host=HOSTNAME;

stringVar=email:name@company.com&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?

Answer

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

Comments