Search code examples
javascriptbookmarklet

How to match a url link and open it, otherwise google search it?


i want to mark a bookmarklet which can match my enter words.

if enter words are url like http://,

then open it,

otherwish use google to search it!

here is my code below, but it seems not working!!

javascript:var x=prompt('Enter url or text!','');
  let url = x;
  try {
    var reg = /^http[s]?:\/\/(www\.)?(.*)?\/?(.)*/;
    if (!reg.test(url)) {
      url = 'https://www.google.com/search?q=' + encodeURIComponent(url);
    }
    else {
      if (url.substring(4, 0).toLowerCase() == "http") {
        url = encodeURIComponent(url);
      }
      else {
        url = 'http://' + encodeURIComponent(url);
      }
    }
  };

use bookmarklet way!


Solution

  • The code is fine, except it fails to match on URLs like www.stackoverflow.com (without the http[s]) and also it's encoding the forward slashes when http[s] is provided.

    • Change regex to also match www.stackoverflow.com
    • Change encodeURIComponent to encodeURI for URLs that already have http[s].
    • Wrap code in IIFE to avoid redeclaration of variables so it can be called more than once.

    Note: This solution won't work for urls such as stackoverflow.com which are missing both the www. and http[s]. prefixes.

    javascript:(function() {
      var x=prompt('Enter url or text!','');
      let url = x;
      try {
          var reg = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/;
          if (!reg.test(url)) {
              url = 'https://www.google.com/search?q=' + encodeURIComponent(url);
          } else {
              if (url.substring(4, 0).toLowerCase() == "http") {
                  url = encodeURI(url);
              }
              else {
                  url = 'http://' + encodeURIComponent(url);
              }
          }
          window.location.href = url;
      } catch(err) {
        console.error(err);
      }
    })();