If I pass a string as "testabc#" it breaks somewhere on the way route to the controller. I'm not sure why the # is causing me the issue. Is this a key work in JavaScript causing the issue? I have tried all other different specials characters and they work just fine. Has anyone else come across this issue.
`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`,
Anchor (#) is a feature of URL called fragment and it is used for internal page references. Using a question mark (?) and ampersand (&) can break your HTTP request like an anchor does because all of these things are URL features and it changes URL behavior.
To avoid this kind of error you must use encodeURI() or encodeURIComponent() like below:
with encodeURIComponent():
var url = `/api/Controller/UpdatePassword?currentPassword=${encodeURIComponent(currentPassword.value)}&newPassword=${encodeURIComponent(newPassword.value)}&confirmPassword=${encodeURIComponent(confirmPassword.value)}`
with encodeURI():
var url = encodeURI(`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`)
# in a url is a special character which indicates a "fragment", which means a special part of the url which is an anchor in the page, of sorts. Thats why it breaks your code. ? And & are also special, and so are a few others.
You should url encode data that you pass in the url.
Try use encodeURI() to the url string before fetching, like:
var url = `/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`
encodeURI(url)
Related
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')
I have a string that may contain several url links (http or https). I need a script that would remove all those URLs from the string completely and return that same string without them.
I tried so far:
var url = "and I said http://fdsadfs.com/dasfsdadf/afsdasf.html";
var protomatch = /(https?|ftp):\/\//; // NB: not '.*'
var b = url.replace(protomatch, '');
console.log(b);
but this only removes the http part and keeps the link.
How to write the right regex that it would remove everything that follows http and also detect several links in the string?
Thank you so much!
You can use this regex:
var b = url.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');
//=> and I said
This regex matches and removes any URL that starts with http:// or https:// or ftp:// and matches up to next space character OR end of input. [\n\S]+ will match across multi lines as well.
Did you search for a url parser regex? This question has a few comprehensive answers Getting parts of a URL (Regex)
That said, if you want something much simpler (and maybe not as perfect), you should remember to capture the entire url string and not just the protocol.
Something like
/(https?|ftp):\/\/[\.[a-zA-Z0-9\/\-]+/
should work better. Notice that the added half parses the rest of the URL after the protocol.
I'm trying to validate a field to allow relative and absolute urls. I'm using the regex from this post but it is allowing spaces in the url.
var urlRegex = new RegExp(/(\/?[\w-]+)(\/[\w-]+)*\/?|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?)/gi);
Example:
// this should work
this/will/work.aspx?say=hello
http://www.example.com/this/will/work.aspx?say=hello
// this shouldn't work but does
and/this will also work/even though it shouldn't
and/this-shouldn't/but it does/also
The code below is what I was originally using to validate just absolute urls and it was working perfectly. If I remember properly, I pulled it from the jquery source. If this could be modified to also accept relative urls that would be perfect, but this is out of my league.
var urlRegex = new RegExp(/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/i);
I think you just need to anchor the pattern so that it has to match the whole string:
var urlRegex = /^(\/?[\w-]+)(\/[\w-]+)*\/?|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?)$/gi;
The leading ^ and trailing $ means that the pattern has to match the entire string instead of just some part of it.
edit that said, the pattern has other problems. First, those HTML entities for & (&) need to be just "&". The slashes don't need to be escaped in [] groups, and we don't need the "g" suffix. That leaves us with:
var urlRegex = /^(?:(\/?[\w-]+)(\/[\w-]+)*\/?|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)*([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?))$/i;
edit again - oops also need to wrap the whole thing.
I wrote an article about URI validation complete with code snippets for all the various URI components as defined by RFC3986 here:
Regular Expression URI Validation
You may find what you are looking for there. Note however that almost any string represents a valid URI - even an empty string!
I have a Spring-MVC application with Freemarker as the view component.
In my templates, several links are generated which point back to my application and which include URL parameters containing a hash key (#).
Example:
parameter: Q#106368 11
URL generated by Freemarker with encoded param: testurl.html?key=Q%23106368%2011
I use JavaScript to redirect to this URL (reason: I use JS to manage loading of 2 frames at the same time).
The redirect method is simple:
function redir(url) {
window.location.href = url;
}
The JS call generated by Freemarker looks like
test
My problem is that the browser / Javascript converts back the URL encoded parameter, thinks there is a # and cuts off there.
When I use window.location.href='http://...' directly it works. Only when using the method parameter it seems to be magically URL decoded and then the redirect fails because the URL gets cut off at the #.
Is there an easy way to transmit the parameter correctly?
I am aware that I could replace the #, e.g. with $$$hash$$$, in the template and do the replacement on the server side again. But there are so many places I would have to change...
As Marc B commented, it is necessary to URL encode again. The method would be encodeURI(). However, this method does not encode the # sign. For my specific use case, I have to replace the # sign with %23 after the encoding.
The redirect JS method finally looks like:
function redir(url) {
url = encodeURI(url);
url = url.replace(/#/g, '%23');
window.location.href = url;
}
Comparing escape(), encodeURI(), and encodeURIComponent()
encodeURIComponent/decodeURIComponent is more thorough than just encodeURI, it will decode/encode '#' and event '/'
What browser are you using? I'm trying FireFox 5 and it doesn't convert %23 back into # in my testing. When you mouse over the link or copy the link location, what does that have? Are you sure whatever is outputting the link isn't doing the conversion?
Update
This isn't ideal, but it seems like it solves the problem:
<a onclick="url = 'http://localhost:8080/testappp/testurl.html?key=Q%23106368%2011';" href="javascript:redir(url);">test</a>
It seems like the href attribute is decoded. When I mouse over it I seen the # instead of the %23.
Problem
I am trying to match the hash part of a URL using Javascript. The hash will have the format
/#\/(.*)\//
This is easy to achieve using "new RegExp()" method of creating a JS regular expression, but I can't figure out how to do it using the standard format, because the two forward slashes at the end begin a comment. Is there another way to write this that won't start a comment?
Example
// works
myRegexp = new RegExp ('#\/(.*)\/');
// fails
myRegexp = /#\/(.*)\//
I am trying to match the hash part of a URL using Javascript.
Yeah, don't do that. There's a perfectly good URL parser built into every browser. Set an href on a location object (window.location or a link) and you can read/write URL parts from properties hostname, pathname, search, hash etc.
var a= document.createElement('a');
a.href= 'http://www.example.com/foo#bar#bar';
alert(a.hash); // #bar#bar
If you're putting a path-like /-separated list in the hash, I'd suggest hash.split('/') to follow.
As for the regex, both versions work identically for me. The trailing // does not cause a comment. If you just want to appease some dodgy syntax highlighting, you could potentially escape the / to \x2F.
It is not starting a comment, just like two slashes in a string. Look here: http://jsfiddle.net/Gr2qb/2/