How to get query string values in JavaScript containing special characters?

1.8k views Asked by At

I have followed the answer from this great post: How can I get query string values in JavaScript?

However, the issue I am having is that on some occasions, my query string values could contain special characters, for example * + - / etc eg:

?userid=de+8d49b7*8a85a3/222343

The above function does not cater to these. How can I get the query string values and inc the special characters? I have tried:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var prodId = encodeURIComponent(getParameterByName('prodId'));

The solution must work in IE8+ too.

2

There are 2 answers

0
kevinkl3 On

This should do the trick:

function getParameterByName(name,ovr) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(ovr || location.search);
    return results === null ? "" : decodeURIComponent(results[1]);
}

var prodId = getParameterByName('prodId','?prodId=de+8d49b7*8a85a3/222343&userId=23243*--++/231');
console.log('Url: ?prodId=?prodId=de+8d49b7*8a85a3/222343&userId=23243*--++/231\nprodId: ' + prodId);

Just remove this .replace(/\+/g, " ") from the returning statement so you could have + characters instead of ""(spaces).

Is important to note that this will introduce ambiguity to the values you're getting because the URLs can't have spaces so when you encode an URL it will have + characters instead of spaces. If you're willing to use this method you must be sure that all the values that you're retrieving don't have spaces.

1
Silambarasan A On

Use the code below to remove special characters in your query string.

var value="testdkldskdskkd@#$$%^dsjse"
var cleanString = value.replace(/[/^]/g, "");
console.log(cleanString)