Is it possible to parse a URL parameter in a trans...
# support
a
Is it possible to parse a URL parameter in a transformation? I can't find any example in the sample transformation repo. I tried to call
URLSearchParams
but it is not defined.
h
did you create a url object first?
a
No. I tried to do this in the transformation:
Copy code
const search = event.context?.page?.search;
    if (search)
    {
        const params = new URLSearchParams(search);
        const foo = params.get("foo");
        log("The value of foo is", foo);
    }
and received this output:
Copy code
{
  "error": "ReferenceError: URLSearchParams is not defined"
}
Hi @shy-kite-21035 - Any update on this?
Hi @shy-kite-21035 - Any update on this?
g
Hi @agreeable-australia-13022, we do not support
URLSearchParams
out of the box in transformer code. So the error shown is correct, there's no such object named
URLSearchParams
. We can take this as a feature request, for this, please create an issue on GitHub And meanwhile, you do need to create the functionality of URLSearchParams yourself. I am sharing a code sample snippet which can help you get started with that
Copy code
const searchParams = e.context.page ? e.context.page.search : undefined;
    if(searchParams) {
        const indvSearchParams = searchParams.trim().split('&');  // ?test1=val1&test2=val2
        if(indvSearchParams.length > 0) {
            const firstSearchString = indvSearchParams[0].slice(1, indvSearchParams[0].length); // remove the preceding '?'
            indvSearchParams[0] = firstSearchString;
            
            indvSearchParams.forEach(valSearch => {
                var keyValPairs = valSearch.split("="); // seperate key and val
                if(keyValPairs[0].length > 0) {
                    if(!e.context.traits) {
                        e.context.traits = {};
                    }
                    // will be e.context.traits[keyValPairs[0]] = keyValPairs[1], for now keeping key "UTM" and overiding
                    if (keyValPairs[0] === 'type') {
                        e.context.traits["UTM"] = keyValPairs[1]; 
                    }
                    if (keyValPairs[0] === 'utm_campaign') {
                        e.context.traits["UTMCMPG"] = keyValPairs[1]; 
                    }
                    
                }
            })
        }
         
    }
Please do create an issue on GitHub requesting support for
URLSearchParams
out of the box so you can be notified when we release this. And also this can help other community members contribute to the discussion.