#&q=car&category=Car%20Audio%2CAccessories&brand=
I borrowed a this function from a previous question asked on SO:
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.hash.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.hash = kvp.join('&');
}
I use it like this:
insertParam("category",xy);
insertParam("brand",zy);
My problem is it is decoding comma's to %2C. I know I can handle the characters on the server side, but how can I make it look pretty with javascript? By pretty I mean replace %2c with a comma.
JS replace all commas in Strings The best way is to use regular expression with g (global) flag. var myStr = 'this,is,a,test'; var newStr = myStr.replace (/,/g, '-'); console.log (newStr); // "this-is-a-test" Q: How to Replace multiple strings with multiple other strings in Javascript?
The replace () method find a string for a specified input, or a regular expression, and returns a new string where the specified input is replaced. In the example, we are replacing a “JS” word with “JavaScript”.
There are numerous ways to replace the semicolon with comma. We are going to use the simplest approach which involves the usage of the regex pattern as well as replace () method.
You can do modifications on a string using JavaScript replace method. replace method is an inbuilt function in JavaScript which is used to change particular character, word, space, comma, or special char in Strings. How it’s work?
I do not know why in the previous answer that was striked out, but the answer was correct.
alert(decodeURIComponent('%2C'));
So, you break your query strings into elements, splitting by & symbol. Than you split the results by = symbol and apply decodeURIComponent on both name and the value.
ps: key = escape(key); value = escape(value);
you should not use escape here (it is different for different browsers. and by 'different' I meant IE). Use encodeURIComponent.
pps: because they either encode commas or don't encode &=
???
alert(encodeURIComponent('&=,'));
outputs %26%3D%2C
This worked for me for undoing encodeURIComponent()
on URIs that contain commas:
.replace(/%2C/g,",")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With