user2727195 user2727195 - 4 months ago 15
Javascript Question

regular expression to extract different parts of a url

I've a set of different urls with similar pattern and I need to extract the following from each using a regex in javascript. Is it possible to extract different pieces in one command?


  1. UUID

  2. documenttype

  3. document name (demo in this case)

  4. images/thumbnail?size=768 or images/thumbnail or images/background

  5. thumbnail or background

    /document/b5bacc1e-7b55-4263-97a5-ca7015e367e0/word/demo/con;version=99/images/thumbnail?size=768

    /document/b5bacc1e-7b55-4263-97a5-ca7015e367e0/excel/demo/con;version=99/images/thumbnail?size=100

    /document/b5bacc1e-7b55-4263-97a5-ca7015e367e0/powerpoint/demo/con;version=99/images/thumbnail

    /document/b5bacc1e-7b55-4263-97a5-ca7015e367e0/word/demo/con;version=99/images/background?size=100

    /document/b5bacc1e-7b55-4263-97a5-ca7015e367e0/excel/demo/con;version=99/images/background



My attempt.

url.match(/images\/(.*)/);

Answer

Assuming the structure will always be as the examples you gave, you can use:

matches = url.match(/(([a-f0-9]+\-)+[a-f0-9]+)\/(.*?)\/(.*?)\/.*(images\/([^\?]*).*$)/);
result = {
    "UUID": matches[1],
    "documentType": matches[3],
    "documentName": matches[4],
    "image": matches[5],
    "imageType": matches[6]
}
Comments