JavaScript Regex To Get Parts Of URL

I came across an extremely useful JavaScript Regex To Get Parts Of URL lately that I thought I would document as it took some searching to find. Basically I was trying to find the host of any number of combinations of urls. Meaning, if you have https://www.adamthings.com/ I wanted to then only get adamthings.com back.

The use case for this was I need to ensure the host domains matched. So if I got an input of say http://www.alienwarefxthemes.com/ I wanted to fail it because adamthings.com does not equal alienwarefxthemes.com.

Now I realize this regex may be a bit overkill for this situation but it was one of the few that seem to handle the majority of my cases successfully.

Now, the regex. I’ll be the first to admit I don’t understand everything that is going on as I didn’t write it and regex are not my thing.

var _host_from_url = function (url) {
var clean_url = jq.trim(url);
var match = clean_url.match(/^((http[s]?|ftp):\/\/)?\/?([^\/\.]+\.)*?([^\/\.]+\.[^:\/\s\.]{2,3}(\.[^:\/\s\.]‌​{2,3})?)(:\d+)?($|\/)([^#?\s]+)?(.*?)?(#[\w\-]+)?$/i);

return match[4];
};

Sorry for the wrapping, but I wanted it to all be on the screen without scrolling. So in my case, I was returning the 5th part of the array as it was the host name. Lets look at some outcomes.

Url To Test:
https://www.adamthings.com/post/2014/02/17/hello-world-angularjs/ has 10 groups:

  1. http://
  2. http
  3. www.
  4. adamthings.com
  5. /
  6. post/2014/02/17/hello-world-angularjs/

As you can see there is a lot more information you can gather from this regex. I recommend playing with it and seeing how it works for you. Here are some other examples. (Left out the blanks to conserve space but you can see the url used and what parts it found.

www.adamthings.com has 10 groups:
www.
adamthings.com

http://www.subdomain.adamthings.com has 10 groups:
http://
http
subdomain.
adamthings.com

https://www.adamthings.com has 10 groups:
https://
https
www.
adamthings.com

adamthings.com has 10 groups:
adamthings.com

https://www.adamthings.com has 10 groups:
http://
http
adamthings.com

https://www.adamthings.com has 10 groups:
https://
https
adamthings.com

JavaScript Operators Challenge Question

JavaScript Operators Challenge Question that I stumbled upon from Stackoverflow and wanted to share it here to have as a fun challenge question.

The question is: In JavaScript, why does this equal 42?

[(0>>(0==0))+([0]+[(0==0)+(0==0)]^0)]*[(0^[(0==0)+(0==0)]+[0])+((0==0)<<0)]

Give it some thought. Have you figured it out yet?

Here is the explanation given at StackOverflow

The basic elements are as follows:

0==0

This is true, which can be coerced in to 1.

a >> b

The right-shift operator. In this case, it’s only used at the beginning of the expression as 0 >> 1 which evaluates to 0.

a^b

Bitwise XOR. Both usages above have either a or b are 0, and so the result is the non-zero operand.

[a] + [b]

String addition of a and b, evaluates to “ab”; if both a and b are numeric (e.g. [0]+[1] the result can be coerced into a numeric.

[a] * [b]

Multiplication can be performed on single element arrays, apparently. So this is equivalent to a*b.

Finally,

a << b

The left-shift operator; for positive integers this effectively multiplies by 2 to the power of b. In the expression above, this is used with b = 0, so the result is a.

If you apply the correct order of operations, you get out [2] * [21] which evaluates to 42.

Send it to your friends, see how good they are with JavaScript operators.

Create Custom KnockoutJS Binding For Enter Key Press

Today I had to add an event to an input box that when the user hits enter on the keyboard, it would call a JavaScript function. However, it’s pretty easy to do with a onkeypress=”” but it still uses a lot of other JavaScript and jQuery. I wanted to do this with using a custom KnockoutJS binding for the enter key so lets take a look at the mark up first.

//Field for typing. enterKey is the name of the custom binding.
<input id="name" data-bind="value: name, enterKey: addName" /> 

//This is the button for if they click instead of enter.
<input id="addName" type="button" data-bind="click: addName" value="Add" /> 

Take notice that in the first line and in the second like they are both pointing to the same function addName. Now lets take a look at the custom binding called enterKey.

// Custom Binding
ko.bindingHandlers.enterKey = {
  init: function (element, valueAccessor, allBindings, data, context) {
    var wrapper = function (data, event) {
      if (event.keyCode === 13) {
        valueAccessor().call(this, data, event);
      }
    };
    ko.applyBindingsToNode(element, { event: { keyup: wrapper } }, context);
  }
};

The cool thing about this customer knockoutjs binding is that you could pass it any function to call. All you would have to do in the markup is data-bind="enterKey: aDifferentFunction" and it would work the same. This obviously works great if you have multiple instances where you would like to check the enter key press and do a certain function without having to do a ton of checking of what’s calling what.

This was answered by Dennis on StackOverflow when I asked how to convert javascript onkeypress to knockoutjs to call on enter.

How to find an element in an observable array in KnockoutJS

How to find an element in an observable array in KnockoutJS is not that hard of a task.  This is assuming that the two items you are comparing are a reference to the same item.  This is more of a custom comparison function to compare a value in an array to some other value.  To complete this we will use the ko.utils.arrayFirst from KnockoutJs.

Take a look at the following Javascript:

var match = ko.utils.arrayFirst(myObservableArray(), function(item) {
    return someValue.name === item.name;
});

Essentially what is happening here is that knockout is combing through the myObservableArray and looking for a match on name. If it finds a match then it returns that object as match. (Just wait, it’ll make sense). If it doesn’t find anything, then match is returned as undefined.

Here is the second part that deals with the match logic:

if (!match) {
  myObservableArray.push(someValue);
}

If match has a value to it and you apply the ! operator the outcome is false.

If match is undefined and you apply the ! operator the outcome is true.

So overall all, if our someValue does not exist in our myObservableArray, then we add it.


Error Messaging Using KnockoutJS Observable Applying CSS

When doing error messages in an application I like to use KnockoutJS Observable to apply a css class to an input box to color it red meaning it’s required. The concept is quite simple really. You have an observable for the field.

self.FirstNameValidation = ko.observable('');

The point is when your validation fails, you add a message to the observable.

if(self.FirstName() == ''){
      self.FirstNameValidation('First Name Is Required');
}

So now that we have our observable set with an error message we can add a data-bind event to the input box to apply a css class to it.

<input id="firstName" data-bind="value: FirstName, css: { 'validationerror': FirstNameValidation() }">

Looking at the example above, the css class ‘validationerror’ will be added to the input box if there is a value in FirstNameValidation(). Simple way to add a visual cue to an input element that something is missing.

StackOverflow Profile