Force https in Javascript

if (location.protocol != 'https:') {
  var url = window.location.href;
  var pattern = /localhost/;
  if(url.match(pattern) == null){
    location.href = 'https:' + url.substring(window.location.protocol.length);
  }
}