Interested in a ServiceNow event built for developers? Registration for now[dev]26 is officially open!

Parsing URL Parameters from Client Script - Unnecessary Escape Characters

Not applicable

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

Not applicable

Hi @Community Alums,

 

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]);
    }  
}

 

View solution in original post

1 REPLY 1

Not applicable

Hi @Community Alums,

 

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]);
    }  
}