Parsing URL Parameters from Client Script - Unnecessary Escape Characters

G24
Kilo Sage

JavaScript Gurus,

 

Based on the SNCGuru article here:

https://servicenowguru.com/scripting/client-scripts-scripting/parse-url-parameters-client-script/ 

 

I see the following short script:

function getParameterValue(name) {  
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");  
    var regexS = "[\\?&]" + name + "=([^&#]*)";  
    var regex = new RegExp(regexS);  
    var results = regex.exec(top.location);  
    if (results == null) {  
        return "";  
    } else {  
        return unescape(results[1]);  
    }  
}

 

...But the script editor is complaining of some errors on the "name.replace" line...

Can someone help me fix up this script so there are no errors or warnings?

zz.png

I'm not totally clear on what the Intention was.  Thank you!!

1 ACCEPTED SOLUTION

Peter Bodelier
Giga Sage

Hi @G24,

 

The intention was to escape characters which should normally be escaped in a regex. However because of the way the characters are used here, there's no need to escape.

 

unescape is a deprecated function. You should use decodeURI instead.

 

You can use it like this:

 

 function getParameterValue(name) {  
    name = name.replace(/[[]/, "\\[").replace(/[\]]/, "\\]");  
    var regexS = "[\\?&]" + name + "=([^&#]*)";  
    var regex = new RegExp(regexS);  
    var results = regex.exec(top.location);  
    if (results == null) {  
        return "";  
    } else {  
		return decodeURI(results[1]);
    }  
}

 


Help others to find a correct solution by marking the appropriate response as accepted solution and helpful.

View solution in original post

1 REPLY 1

Peter Bodelier
Giga Sage

Hi @G24,

 

The intention was to escape characters which should normally be escaped in a regex. However because of the way the characters are used here, there's no need to escape.

 

unescape is a deprecated function. You should use decodeURI instead.

 

You can use it like this:

 

 function getParameterValue(name) {  
    name = name.replace(/[[]/, "\\[").replace(/[\]]/, "\\]");  
    var regexS = "[\\?&]" + name + "=([^&#]*)";  
    var regex = new RegExp(regexS);  
    var results = regex.exec(top.location);  
    if (results == null) {  
        return "";  
    } else {  
		return decodeURI(results[1]);
    }  
}

 


Help others to find a correct solution by marking the appropriate response as accepted solution and helpful.