Javascript - "history.pushState" replaces regular "&" with "&". How to avoid it? - javascript

I am doing an AJAX request in Rails and after executing it, I'd like to modify the URL and put there all there parameters.
So this is how I obtained the relative URL in the Rails controller:
#url_params = request.original_fullpath
# => /members/info/detail?currency=usd&year=2016
Then, in the JS file:
console.log("<%= #url_params %>");
# => /members/info/detail?currency=usd&year=2016
So I tried:
var url = "<%= #url_params %>";
var replaced_url = url.replace("&", "&");
# => /members/info/detail?currency=usd&year=2016
but it doesn't work neither.
When I do history.pushState("", "", replaced_url);, in the URL is still the $amp; instead of only &.
How to push the URL without the & characters?
Thank you

I believe by default rails html encodes your output to get the unencoded output try
var url = "<%=raw #url_params %>";

change
var replaced_url = url.replace("&", "&");
to
var replaced_url = url.replace(/&/g, '&');
it seems like, url has multiple &'s, because of which single replacement of string would not work, so consider group replace for such things.
know more about : http://www.w3schools.com/jsref/jsref_replace.asp

Related

Using split to get only the URL without query string in javascript

I want to split the website name and get only URL without the query string
example:
www.xyz.com/.php?id=1
the URL can be of any length so I want to split to get the URL to only
xyz.com
able to split the URL and getting xyz.com/php?id=1
but how do I end the split and get only xyz.com
var domain2 = document.getElementById("domain_id").value.split("w.")[1];
You can use:
new URL()
for example -
var urlData = new URL("http://www.example.org/.php?id=1")
and than
urlData.host
which will only return the hostname
You can use a simple regex with match to capture the host in the way you want:
var url = 'www.xyz.com/.php?id=1';
var host = url.match(/www.(.*)\//)[1];
console.log(host)
Just adding it to other, you can also use this regex expression to capture everything up until the query string "?" like so;
This will also work if you want to grab any sub pages from url before the query string
var exp = new RegExp('^.*(?=([\?]))');
var url = exp.exec("www.xyz.com/.php?id=1");
var host = url[0];
console.log(host);

how to filter "\" from a json string in javascript

I receive a json string at my node js server which looks like this:
{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}
The reason i put in the "\" is because the string is made in C and the \ is used to escape the " which otherwise ends the string.
The code i use now is:
app.get('/add/:jsonString', function(req, res){
var json = JSON.parse(req.params.jsonString);
});
Is there a way to only delete the \'s in my string?
Why do you want to remove it, it's not necessary ?
var a ="{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}";
console.log(JSON.parse(a));
// give Object { gID: 1, sID: 18, T: "Parking" }
EDIT
Use Url encode to pass your get json
var str = encodeURIComponent("{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}");
// send your request
request.get({uri:"website/api?data="+str}, ...
And in server, decode uri then parse
var string = decodeURIComponent(req.query.data);
var obj = JSON.parse(string);
If you want to remove the "\", try the replace method with a regex pattern:
str.replace(/\\/g, "")
The g flag is used to replace all occurences of the char "\", while the first "\" is an escape character.
For further details, consult MDN
I would suggest that you pass JSON into your application using a POST request, as there are plenty of characters that aren't URI-safe.
However, you can use the unescape method from the built in querystring module.
const qs = require('querystring');
app.get('/add/:jsonString', function(req, res){
const json = JSON.parse(qs.unescape(req.params.jsonString));
});

Is it possible to get this part of a string

I wonder if it's possible to get this part of a string.
Here is my string:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
Now I want to be able to grab just this part of the string, the file name:
12391381_10205760647243398_2385261683139818614_n.jpg
I tried:
var result = /[^/]*$/.exec(""+url+"")[0];
, but it will return
user%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=4c92c4d7-8979-4478-a63d-ea190bec87cf
My Regex is wrong.
Another this is, the file extension can be .png or jpg so it's not fixed to jpg.
You could use a regex to isolate the part you want :
This works :
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
console.log((string.match(/[A-Za-z0-9_]+.(jpg|png|bmp)/))[0].substring(2));
Note that may have to be adapted depending on how much the URL string changes:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var out = string.split('?')[0].split('%2F')[2];
console.log(out); // "12391381_10205760647243398_2385261683139818614_n.jpg"
Assuming, you always have an url, first I would decode the encoded / (%2F) characters via:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var decodedUrl = decodeURIComponent(string);
and then use a regex:
decodedUrl.match(/[^/]*(?=[?])/)
Mind, that this regex assumes parameters (the part starting with ?...) are present, so if that's not the case, you might have to alter it to your needs.
If the filename always has a .jpg extension:
var url = decodeURIComponent(string);
var filename = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf(".jpg"))
If not:
url = url.substring(url.lastIndexOf("/")+1)
filename = url.substring(0,url.indexOf("?"))
Looking at the string, it appears that the file name is between the second occurrence of "%2F" and the first occurrence of "?" in the string.
The first step is to get rid of the part of the string before the second "%2F". This can be done by splitting the string at every "%2F" and taking the third element in the resulting array.
var intermediate = string.split("%2F")[2]
Then, we need to get rid of everything after the "?":
var file_name = intermediate.split("?")[0]
This should give you the file name from the URL

Escape Base64 String in URL?

For some reason I need to put a Base64 encoded string in the URL, i.e.
<script>
var URL = "localhost:8080/MyApp/order?z=AAAAAAAEJs4"
</script>
The URL is generated by Java, problem here is I can only use java to make the Base 64 encoded string to be URL friendly, but not javascript friendly, so fire bug give me the following error:
SyntaxError: unterminated string literal
Apparently there are charactors in the Base64 string requires escaping. However I cannot use escape() or URLencoding() method as the request will directly deliver to the controller and manipulated by java code, so there is no "next page" in this situation.
So how to make this work then?
If your're trying to convert that z url attribute into an understandable string/variable, you have to use a library to convert that. Below is a link to a base64 library for Javascript that you must load in.
http://www.webtoolkit.info/javascript-base64.html
You maybe also need a library to access the z attribute in your url. I would recommend this:
https://github.com/allmarkedup/purl
Just in case it helps, here is a short JS code requiring no dependency:
String.prototype.base64EncodeUrl = function () {
var str = this;
str = window.btoa(unescape(encodeURIComponent( str )));
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
};
String.prototype.base64DecodeUrl = function () {
var str = this, str_pad = (str + '===');
str = str_pad.slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
return decodeURIComponent(escape(window.atob( str )));
};

Decoding http link in .NET

I am opening a page from my javascript and passing variable to it like below
<script type="text/javascript">
function myFunction(what) {
var valu = what.value;
var w = window.open("playaudio.aspx?" + what.value);
return false;
}
Now on my playaudio.aspx i am doing this to decode back the %2f and %3f etc into / and ?
string FilePath = HttpUtility.HtmlDecode(Request.QueryString.ToString());
but the problem is that the string FilePath remains unchanged . Any advice on how to change the %2f into / .
That's because URLs are not HTML encoded.
You need UrlDecode.
See HttpUtility.UrlDecode - I believe that's what you're after.

Categories

Resources