I'm wanting to do a check in JavaScript that the URL passed in to redirect to is a relative URL and not an absolute one.
I've looking at doing something similar to this snippet though would like to know if there is a better way of achieving this?
var relativePath = document.location.hash.substring(1); var re = new RegExp("^/[a-z0-9/.]+$"); if (re.test(relativePath)) { document.location = relativePath; }
You can check what the url starts with rather than what it contains, and RegEx isn't required either. Basically, all absolute URL's will start with "http://" or "https://" while relative ones will not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.