AngularJS $location search confused - javascript

This is my url with params look like:
http://localhost:8000/search?city=uk&cat=Sightseeing%20&%20Tours
But when I try to capture the cat params using:
var test2 = $location.search().cat;
it only return Sightseeing. How can I resolve this issues? Thanks!!

The ampersand (&) is the delimiter for URL parameters. This means that the cat parameter ends after Sightseeing%20. (The %20 is probably automatically converted to a space, rendering it invisible.)
There is a simple solution though; just percent-encode the ampersand; use %26. Note most programming languages provide some function to automatically percent-encode strings, in PHP for example it would be urlencode().
For more information, see https://en.wikipedia.org/wiki/Percent-encoding. It talks about reserved and unreserved characters in URLs, which is exactly what's causing your problem; the ampersand is a reserved character.

Related

Why is split and join doing this?

I'm getting some very weird behaviour that I don't understand using JavaScript split and join. I'm sending names with spaces in an API call but using %3 as the delimiter for spaces, as in, if I'm sending "Ammar Ahmed", the API call would look like: api/v1?q=Ammar%3Ahmed. In the server code, when I split it up again with q.split("%3").join(" ") because the database contains names with spaces, for one name in particular: "Ashwini Bettahalsoor", I'm getting "Ashwini;ettahalsoor". I'm very confused why its doing this, its splitting it including the B and joining it with a ; but it works perfectly normal for all names that the last name does not start with B. I'm sure it has something to do with the letter B but first of all I'm curious as to why this is happening and secondly, I'm wondering what I should use instead of %3 for spaces in the API call.
%3 is not the correct encoding for a space. You're getting ; because %3B is the encoding for that character. URI encoding always uses 2 hex digits.
You should use encodeURICompnent() to generate the correct encoding.
let url = 'api/v1?q=' + encodeURIComponent('Ashwini Bettahalsoor');
And on the server you should use middleware that decodes the query parameters for you, rather than using split() and join() explicitly.

Issue with Decoding %20 from URL

I have found that the following thread provides an extremely useful way to create permalinks or to pass string values via a URL:
Original Thread
Unfortunately, if you wanted to pass the string "test string", for example, to a specific <div> via the URL and display it as simple text, the above thread doesn't seem to decode white space if your URL looks like this:
http://www.abc123.org/subpage.html?test%20string
The code will simply take anything in the URL passed the "?" and it will appear as "simple%20text".
Is there a simple way to do something similar to the Thread's accepted answer so that all %20 can be replaced with white space? Thanks!
You can use decodeURI():
Replaces each escape sequence in the encoded URI with the character
that it represents, but does not decode escape sequences that could
not have been introduced by encodeURI. The character “#” is not
decoded from escape sequences.
const result = decodeURI('http://www.abc123.org/subpage.html?test%20string');
console.log(result);

Regular Expression - Extract subdomain & domain

I'm trying to form a regular expression (javascript/node.js) which will extract the sub-domain & domain part from any given URL. This is what I ended up with:
[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)
Right now, I'm just considering http, https for protocol & exclude "www." portion from the subdomain+domain portion of an URL. I checked the expression & it almost works. But, here is the issue:
Success
'http://mplay.google.co.in/sadfask/asdkfals?dk=10'.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)
'http://lplay.google.co.in/sadfask/asdkfals?dk=10'.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)
Failure
'http://play.google.co.in/sadfask/asdkfals?dk=10'.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)
'http://tplay.google.co.in/sadfask/asdkfals?dk=10'.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)
I just use the first element from the result array. I'm not able to understand why "play." & "tplay." doesn't work. Could anyone please help me in this regard?
Does "/p" and "/t" have any meaning for the regular expression evaluator?
Is there any other way of extracting sub-domain & domain from any given URL using a regular expression?
Edit -
Example:
https://play.google.com/store/apps/details?id=com.skgames.trafficracer => play.google.com
https://mail.google.com/mail/u/0/#inbox => mail.google.com
Your regex doesn't seem correct. Try this regex:
/^(?:https?:\/\/)?(?:[^#\n]+#)?(?:www\.)?([^:\/\n?]+)/img
RegEx Demo
You are about the one millionth person to try to parse URLs in JavaScript. I'm a little bit surprised you didn't see any of the existing questions on SO dating back years. The last thing you want to do is write yet another broken regexp, with all due respect to those that provided answers to your question.
There are many well documented libraries and approaches to handling this. Google it. The simplest way is to create an a element in memory, assign it an href, and then access its hostname and other properties. See http://tutorialzine.com/2013/07/quick-tip-parse-urls/. If that does not float your boat, then use a library like uri.js.
If you really don't want to use a library, and insist on reinventing the wheel, then at least do something like the following:
function get_domain_from_url(url) {
var a = document.createElement('a').
a.setAttribute('href', url);
return a.hostname;
}
Essentially, you are delegating the extraction of the subdomain/domain part of the URL to the browser's URL parsing logic, which is MUCH better than anything you will ever write.
Also see Parse URL with jquery/ javascript?, Parse URL with Javascript, How do I parse a URL into hostname and path in javascript?, or parse URL with JavaScript or jQuery. How did you miss those? Sorry, I have to vote to close this as a duplicate.
The same RegExp as in anubhava's answer, only added support for protocol-relative URLs like //google.com:
/^(?:https?:)?(?:\/\/)?(?:[^#\n]+#)?(?:www\.)?([^:\/\n]+)/im
RegEx Demo
Here's a solution ignoring everything before ://
.*\://?([^\/]+)
Incase you want to ignore www.
.*\://(?:www.)?([^\/]+)
Your regex expression works pretty well. You only need to remove the brackets. The final expression is:
^(?:http:\/\/|www\.|https:\/\/)([^\/]+)
Hope it's useful!
I know I am late to the party but I want to answer the question with some extra useful info.
Get the domain name from a link using regex.
^(https?:\/\/)?(www\.)?([^\/]+)
Here is the link to above regex.
If you want to get the subdomain, split the result from one of the matches of above regex with the first occurrence of .
Note: regex is faster than language built-in modules. check below examples, regex comes out to be 15x faster than the built-in module
javascript Example with Regex:
console.time('time2');
const pttrn = /^(https?:\/\/)?(www\.)?([^\/]+)/gm
const urlInfo = pttrn.exec("https://www.google.co.in/imghp");
console.timeEnd('time2');
//time2: 0.055ms
console.log(urlInfo[0]) // https://www.google.co.in
console.log(urlInfo[1]) // https://
console.log(urlInfo[2]) // www.
console.log(urlInfo[3]) // google.co.in
Nodejs with built-in url module
console.time('time');
const url = require('url');
const urlInfo = url.parse("https://www.google.co.in/imghp");
console.timeEnd('time');
//time: 0.840ms;
console.log(urlInfo.hostname) //www.google.co.in

How to make this youtube videoId parsing RegExp work in JS?

I'm trying to use this great RegEx presented here for grabbing a video id from any youtube type url:
parse youtube video id using preg_match
// getting our youtube url from an input field.
var yt_url = $('#yt_url').val();
var regexp = new RegExp('%(?:youtube(?:-nocookie)?\\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\\.be/)([^"&?/ ]{11})%','i');
var videoId = yt_url.match( regexp ) ;
console.log('vid: '+videoId);
My console is always giving me a null videoId though. Am I incorrectly escaping something in my regexp var? I added the a second backslash to escape the single backslashes already.
Scratching my head?
% are delimiters for the PHP you got the link from, Javascript does not expect delimiters when using new RegExp(). Also, it looks like \\. should probably be replaced with \. Try:
var regexp = new RegExp('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})','i');
Also, you can create a regular expression literally by using Javascript's /.../ delimiters, but then you'll need to escape all of your /s:
var regexp = /(?:youtube(?:-nocookie)?\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\\.be\/)([^"&?\/ ]{11})/i;
Documentation
Update:
A quick update to address the comment on efficiency for literal expressions (/ab+c/) vs. constructors (new RegExp("ab+c")). The documentation says:
Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.
And:
Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Since your expression will always be static, I would say creating it literally (the second example) would be slightly faster since it is compiled when loaded (however, don't confuse this into thinking it won't be creating a RegExp object). This small difference is confirmed with a quick benchmark test.

How to identify all URLs that contain a (domain) substring?

If I am correct, the following code will only match a URL that is exactly as presented.
However, what would it look like if you wanted to identify subdomains as well as urls that contain various different query strings - in other words, any address that contains this domain:
var url = /test.com/
if (window.location.href.match(url)){
alert("match!");
}
If you want this regex to match "test.com" you need to escape the "." and both of the "/" that means any character in regex syntax.
Escaped : \/test\.com\/
Take a look for here for more info
No, your pattern will actually match on all strings containing test.com.
The regular expresssion /test.com/ says to match for test[ANY CHARACTER]com anywhere in the string
Better to use example.com for example links. So I replaces test with example.
Some example matches could be
http://example.com
http://examplexcom.xyz
http://example!com.xyz
http://example.com?q=123
http://sub.example.com
http://fooexample.com
http://example.com/asdf/123
http://stackoverflow.com/?site=example.com
I think you need to use /g. /g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one:
var /test.com/g;
If you want to test if an URL is valid this is the one I use. Fairly complex, because it takes care also of numeric domain & a few other peculiarities :
var urlMatcher = /(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?#)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/;
Takes care of parameters and anchors etc... dont ask me to explain the details pls.

Categories