简体   繁体   中英

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

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM