Why if using # in URL with JS it returns ''/false?
var el = '#string with number character -> #'
el = el.replace(/[']/g, ''');
el = el.replace(/[#]/g, ''');
xmlhttp.open("GET","process_add_article.php?&title=" + (el),true);
xmlhttp.send();
If you want to encode a string on the url there is a native method to do so:
var el = '#string with number character -> #';
el = encodeURI(el);
I am not sure this will accomplish what you are looking for though, the url will be:
xmlhttp.open("GET","process_add_article.php?&title=#string%20with%20number%20character%20-%3E%20#",true);
Which means the title parameter is empty, because the server will ignore the hash (#)
Because # specifies a fragment identifier. Fragment identifiers are entirely client side entities and as such are not sent to the server. See Wikipedia on the topic.
You are using Numeric Character Reference and not Percent-Encoding for URIs.
You may want to use encodeURIComponent instead.
var el = '#string with number character -> #';
xmlhttp.open("GET", "process_add_article.php?&title=" + encodeURIComponent(el), true);
xmlhttp.send();
Not to be confused with encodeURI which doesn't encode #, + and = characters.
Related
I want to make sure that the URL I get from window.location does not already contain a specific fragment identifier already. If it does, I must remove it. So I must search the URL, and find the string that starts with mp- and continues until the end URL or the next # (Just in case the URL contains more than one fragment identifier).
Examples of inputs and outputs:
www.site.com/#mp-1 --> www.site.com/
www.site.com#mp-1 --> www.site.com
www.site.com/#mp-1#pic --> www.site.com/#pic
My code:
(that obviously does not work correctly)
var url = window.location;
if(url.toLowerCase().indexOf("#mp-") >= 0){
var imgString = url.substring(url.indexOf('#mp-') + 4,url.indexOf('#'));
console.log(imgString);
}
Any idea how to do it?
Something like this? This uses a regular expression to filter the unwanted string.
var inputs = [
"www.site.com/#mp-1",
"www.site.com#mp-1",
"www.site.com/#mp-1#pic"
];
inputs = inputs.map(function(input) {
return input.replace(/#mp-1?/, '');
});
console.log(inputs);
Output:
["www.site.com/", "www.site.com", "www.site.com/#pic"]
jsfiddle: https://jsfiddle.net/tghuye75/
The regex I used /#mp-1?/ removes any strings like #mp- or #mp-1. For a string of unknown length until the next hashtag, you can use /#mp-[^#]* which removes #mp-, #mp-1, and #mp-somelongstring.
Use regular expressions:
var url = window.location;
var imgString = url.replace(/(#mp-[^#\s]+)/, "");
It removes from URL hash anything from mp- to the char before #.
Regex101 demo
You can use .replace to replace a regular expression matching ("#mp-" followed by 0 or more non-# characters) with the empty string. If it's possible there are multiple segments you want to remove, just add a g flag to the regex.
url = url.replace(/#mp-[^#]*/, '');
The window.location has the hash property so... window.location.hash
The most primitive way is to declare
var char_start, char_end
and find two "#" or one and the 2nd will be end of input.
with that... you can do what you want, the change of window.location.hash will normally affect the browser adress.
Good luck!
specially * and ! characters which are not encoded using encodeUriComponent
As I've said in the comments, you don't have to encode * or ! in a query string. This is perfectly fine, for instance: http://example.com?foo=bar*!
You seem intent on doing it anyway. You can, if you want, but you don't have to.
Here's how you would if it were necessary:
var param = "bar*!";
param = encodeURIComponent(param)
.replace(/\*/g, '%2a') // 2a is the %-encoding of *
.replace(/!/g, '%21'); // 21 is the %-encoding of !
var url = "http://example.com?foo=" + param;
(If you need to unnecessarily encode other characters, you can get the %-encoding value for them like this: "*".charCodeAt(0).toString(16).)
Or actually, we can automate that:
var param = "bar*!";
param = encodeURIComponent(param).replace(/[*!]/g, function(m) {
return "%" + m.charCodeAt(0).toString(16);
});
var url = "http://example.com?foo=" + param;
...just add any others within the character class (the [...] in the regular expression). (This is less efficient, but it's unlikely to matter.)
But if whatever you're passing this parameter to fails with a raw * or !, I would expect it to fail with an encoded one as well.
I'm trying to pass a query string containing special html chars (e.g. <). I have to do
window.location.href = ".."
And on the other page, I have to retrieve this query string using PHP. But when I check it using isset() it returns false!
For example, when i need to escape <p> using JS like this :
function HtmlEncode(s)
{
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
window.location.href = "http://localhost/test.php?t="+HTMLEncode("<p>");
Now the url is: http://localhost/test.php?t=<p>.
When i do echo isset($_GET["t"]);, i get false as a result.
Or even when i try this is a <p> tag, i get $_GET["t"] equals to this is a.
Can anyone tell me what's happening ?
Don't use HTMLEncode() use encodeURIComponent()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
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 )));
};
I have a url like http://www.example.com/folder/file.html#val=90&type="test"&set="none"&value="reset?setvalue=1&setvalue=45"
Now I need to get the portion of url from starting from #, How do I get that, I tried using window.location.search.substr(); but looks like that searches for ? in a url. is there a method to get the value of url after #
How do I also get a portion of url from ampersand &
Thanks,
Michael
var hash = window.location.hash;
More info here: https://developer.mozilla.org/en/DOM/window.location
Update: This will grab all characters after the hashtag, including any query strings. From the MOZ manual:
window.location.hash === the part of the URL that follows the # symbol, including the # symbol.
You can listen for the hashchange event to get notified of changes to the hash in
supporting browsers.
Now, if you need to PARSE the query string, which I believe you do, check this out here: How can I get query string values in JavaScript?
To grab the hash:
location.hash.substr(1); //substr removes the leading #
To grab the query string
location.search.substr(1); //substr removes the leading ?
[EDIT - since you seem to have a sort query-string-esq string which is actually part of your hash, the following will retrieve and parse it into an object of name/value pairings.
var params_tmp = location.hash.substr(1).split('&'),
params = {};
params_tmp.forEach(function(val) {
var splitter = val.split('=');
params[splitter[0]] = splitter[1];
});
console.log(params.set); //"none"
This will get the # and & values:
var page_url = window.location + ""; // Get window location and convert to string by adding ""
var hash_value = page_url.match("#(.*)"); // Regular expression to match anything in the URL that follows #
var amps; // Create variable amps to hold ampersand array
if(hash_value) // Check whether the search succeeded in finding something after the #
{
amps = (hash_value[1]).split("&"); // Split string into array using "&" as delimiter
alert(amps); // Alert array which will contain value after # at index 0, and values after each & as subsequent indices
}