Search code examples
javascriptxmlnetsuiteencodeuricomponent

Using encodeURIComponent in JavaScript to encode URL variable, but then decode to write?


I've got a weird situation where I'm trying to dynamically construct a URL string in an XML document using JavaScript. I've figured out how to use encodeURIComponent to assemble my URL parameters using ampersands in a string and construct to the URL that I need. However, I need to write the URL to the page as a decoded string because otherwise, visiting that URL doesn't execute the actions I need to correctly. The whole document is constructed in JavaScript, so it has to be in a JavaScript environment.

For instance, I have the following URL that I'm able to assemble in order for the XML to render correctly:

http://www.myurl.com/product-name?itemcolor=2%26size=7

However, I need to turn it back into this as a link in the XML doc:

http://www.myurl.com/product-name?itemcolor=2&size=7

Is that possible? Does that make sense?

Here's my code snippet so far:

var baseURL = 'http://myurl.com', urlappend = '', colorid, sizeid;

function getVariants(item) {
    variants = '<variant>';
        if ("custitem109" in item['columns']){
            colorid = item['columns']['custitem109']['internalid'];
            urlappend += '?itemcolor=' + colorid;
        }
        if ("custitem110" in item['columns']){
            sizeid = item['columns']['custitem110']['internalid'];
            urlappend +=  colorid ? encodeURIComponent('&') + 'size=' + sizeid : '?size=' + sizeid;
        }

        if (typeof item['columns']['urlcomponent'] !== 'undefined' && urlappend !== '') {
            variants += '<action_url>' + baseURL + '/' + item['columns']['urlcomponent'] + urlappend + '></action_url>';
        }

    variants += '</variant>';
    return variants;
}

(this function gets looped through multiple times to construct a portion of the XML feed)

This is a NetSuite suitelet if that makes any difference or if anyone has any question as to why this all has to be in a JS environment.

Any help provided would be very much appreciated.


Solution

  • Actually what you want to do is construct your URLs properly and then xml escape them.

    e.g:

    http://www.myurl.com/product-name?itemcolor=2&size=7
    

    becomes

    http://www.myurl.com/product-name?itemcolor=2&amp;size=7
    

    Any free text should be run through nlapEscapeXML

    nlapiEscapeXML('http://www.myurl.com/product-name?itemcolor=2&size=7');