I am trying to change url with pushstate in java script and my url doesn't have any space or bad character for url but java script encode it and add some character in it.
my code is:
name= name.trim();
const nextState = { additionalInformation: name };
window.history.pushState(nextState, "", my_domain()+"/brands/" + name);
my url is:
http://localhost/brands/Brilliance
but it show as:
http://localhost/brands/Brilliance%E2%80%8C
The '%E2%80%8C' at the end of your URL is an invisible Unicode/ASCII character that you are likely copying when you have pasted in the URL, or maybe a package is causing it. In either case, here are two ways you can solve this:
You can paste your link into a hex editor and remove the invisible character manually before copy-pasting back into your code editor.
You can use this javascript solution to remove the characters:
function remove_non_ascii(str) {
if ((str===null) || (str===''))
return false;
else
str = str.toString();
return str.replace(/[^\x20-\x7E]/g, '');
}
console.log(remove_non_ascii('äÄçÇéÉêHello-WorldöÖÐþúÚ'));
The provided code has no reason to not work, but I have a suspicion that in fact name is malformed. If I get the %E2%80%8C suffix in the URL and run it trough decodeURI, I get an empty string. However, if I manually convert it to the string \xe2\x80\x8c, I get the following: â\x80\x8C. This most probably means corrupted data.
Change your URL using encodeURIComponent
const nextState = encodeURIComponent('http://localhost/brands/Brilliance');
history.pushState({}, '', nextState);
This will change your url and the URL will not have any spaces and bad characters
Related
How could I merge both those regular expressions? This is interesting because it would allow to match the beginning of a string and the end without touching the content in the middle.
function cleanURL(url) {
url = url.replace(/^(?:https?:\/\/)?(?:www\.|ww\d\.|w\d\d\.)?/, '')
url = url.replace(/(\/.*)/, '')
return url
}
console.log(cleanURL('https://hello-world.example.tld/yello-blue/green'))
Result: hello-world.example.tld
Rather than trying to use regex to tease out parts of URLs just use the URL class:
new URL("https://hello-world.example.tld/yello-blue/green").hostname
That doesn't mean it can't be done with a regex, you just need to look for whatever is between // and /.
All this said, I'm not sure what your actual intent is, because there's a bunch of shenanigans with www etc. The URL approach won't filter, it'll just return the hostname.
$.ajax({
url: "/api/v1/cases/annotations/" + case_id + "/" + encodeURIComponent(current_plink),
I am using encodeURIComponent to escape slash. But it does not work for me. This code convert "slash" to "%2F" but apache does not recognize it.
My php part like this :
$app->get('/cases/annotations/:case_id/:prep_name', 'authenticatePathologist', function($case_id, $prep_name) use ($app) {
If i try to send parameter which include slash, it returns page not found.
But if i try to send parameter which does not include slash, it returns OK.
You should encode it twice with encodeURIComponent, i.e. encodeURIComponent(encodeURIComponent(current_plink)). If you encode it only once, the server decodes it, and it's the same as not encoding it at all.
you should follow
AllowEncodedSlashes Directive
I too had a similar issue with url like:
?filters=new:item:text
where it required to escape the colons. for that I tried replacing it to format
?filters/:items/:text but that couldn't work as the Chrome was NOT encoding the '/' value.
Tried the js [escape() method][1] and it worked like charm.
let url = 'https://dev.test.something?filters=';
let filterString = 'new:item:text';
url = url + escape(filterString);
Output:
https://dev.test.something?filters=new%3Aitem%3Atext
Hope this finds helpful!!
I have an MVC application that makes an API call in an onclick event
#Model.MyApiCall is a string that looks something like this:
window.location = 'http://localhost/myPath?myImagePath=http://myimagepath&width=360&category=2'
This successfully calls my API. So far so good.
However, for some reason everything after & is getting cut off from myImagePath. So instead of myImagePath equaling what was sent from my click, I'm only getting this:
http://myimagepath
You have to encode your query string parameter. You can do it in javascript:
window.location = 'http://localhost/myPath?myImagePath=' + encodeURIComponent('http://myimagepath') + '&width=360&category=2'
using encodeURIComponent.
You can also do it inside your MVC controller using HttpUtility.UrlEncode only on the http://myimagepath part of your Model.MyApiCall.
[Edit]
If your myImagePath parameter is the entire http://myimagepath&width=360&category=2 string then of course Steve Danner is right and you should follow his answer.
The ampersand (&) is a special character and needs to be encoded to be properly parsed by the browser. You'll need to break up your query string and actual path into separate strings. Something like this:
<a href="javascript://" onclick="#(Model.MyApiCallPath +
HttpUtility.UrlEncode(Model.MyApiCallQueryString))"></a>
Your final js will look something like:
window.location = 'http://localhost/myPath?myImagePath=http%3A%2F%2Fmyimagepath%26width%3D360%26category%3D2';
You are trying to pass a url as a url parameter. Since the url in question contains special characters, you need to escape/encode the uri components.
Since you're using ASP.Net, you should wrap the string with:
window.location = Uri.EscapeUriString('http://localhost/myPathmyImagePath=http://myimagepath&width=360&category=2')
Weird one but is it possible to make Link work without the text helloworld.com being in the source?
Long story but I have function breaking helloworld because it matches it and I remember back to my AOL days where you could "encode" a url to look completely different text but it still took you to that url? Note I dont mean encoding the ? or = etc - but the actual text of domain name... have I completely imagined this?
Weird one but is it possible to make Link work without the text helloworld.com being in the source?
To what end? If you want to totally prevent users from figuring out the URL before they click the link, no that's impossible. If instead you just want to prevent that URL from being picked up by scrapers that don't run JavaScript, then yes that is entirely possible.
What I would do in that case is add a data attribute to the link with an encoded version of the URL.
Link
Then in your JavaScript, decode. Untested jQuery example to get you started:
$('a[data-href-rot13]').each(function (index, el) {
$(this).attr('href', rot13($(this).attr('data-href-rot13')));
});
Of course, you might want a different algorithm than rot13. You could use AES and base-64 encode the output for use in the tag. In case you do want rot13, see this post: https://stackoverflow.com/a/15747894/362536
You can url encode your URL:
(here just on the 'l' character)
Hello World !
It's not an encryption, but a simple encoding. Url cannot use all characters inside of them, so special chars can be passed with the form %XX where XX is the hexadecimal representation of the char.
You browser will decode it, before using it. This coding is normally seen after the url for params and path (ie: url.com/this%20space), but it is also available inside the domain name.
You can encode an url like that with this short javascript:
var encodeUrl = function(url) {
return url.split('//')[0] + '//'
+ url.split('//')[1]
.replace(/[a-z ]/gi, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
url = 'http://www.helloworld.com/';
encodedUrl = encodeUrl(url)
document.body.innerHTML = 'Raw url: <pre>' + url + '</pre>EncodedUrl: <pre>' + encodedUrl + '</pre>Result: TEST';
I have an issue with submitting post data. I have a form which have a couple of text fields in, and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string like
title=test&content=some content
which is then submitted to the server. The problem I had is when I have '&' (eg  ) entered into one of the inputs which then breaks up the query string. Eg:
title=test&content=some content  
How do I get around this?
Thanks in advance,
Harry.
Run encodeURIComponent over each key and value.
var title = "test";
var content = "some content   ";
var data = encodeURIComponent('title') + /* You don't actually need to encode this as it is a string that only contains safe characters, but you would if you weren't sure about the data */
'=' + encodeURIComponent(title) +
'&' + encodeURIComponent('content') +
'=' + encodeURIComponent(content);
Encode the string..when you want to encode a query string with special characters you need to use encoding. ampersand is encoded like this
title=test&content=some content %26
basically any character in a query string can be replaced by its ASCII Hex equivalent with a % as the prefix
Space = %20
A = %41
B = %42
C = %43
...
You need to encode your query to make it URL-safe. You can refer to the following links on how to do that in JS:
http://xkr.us/articles/javascript/encode-compare/
http://www.webtoolkit.info/javascript-url-decode-encode.html
You said:
...and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string...
In the section where you are building the query string you should also run the value of each input through encodeURIComponent() as David Dorward suggested.
As you do - be careful that you only assign the new value to your processed query string and NOT the form element value, otherwise your users will think their input was somehow corrupted and potentially freak out.
[EDIT]
I just re-read your question and realized something important: you're encoding an   ;character. This is probably a more complicated issue than other posters here have read into. If you want that character, and other &code; type characters to transfer over you'll need to realize that they are codes. Those characters &, n, b, s, p and ; are not themselves the same as " " which is a space character that does not break.
You'll have to add another step of encoding/decoding. You can place this step either before of after the data is sent (or "POSTed").
Before:
(Using this question's answers)
var data = formElement.value;
data = rhtmlspecialchars(data, 0);
Which is intended to replace your "special" characters like with " " so that they are then properly encoded by encodeURIComponent(data)
Or after:
(using standard PHP functions)
<?PHP
$your_field_name = htmlspecialchars_decode(urldecode($_POST['your_field_name']));
?>
This assumes that you escaped the & in your POST with %26
If you replaced it with some function other than encodeURIComponent() you'll have to find a different way to decode it in PHP.
This should solve your problem:
encodeURIComponent(name)+'='+encodeURIComponent(value)+'&'+encodeURIComponent(name2)+'='+encodeURIComponent(value2)
You need to escape each value (and name if you want to be on the safe side) before concatenating them when you're building your query.
The JavaScript global function encodeURIComponent() does the escaping.
The global function escape() (DOM) does this for you in a browser. Although people are saying it is not doing the escaping well for unicode chars. Anyway if you're only concerned about '&' then this would solve your problem.