简体   繁体   中英

Display BitLy Shortened URL in Base64

I would like to display the (result) of the below code in base64.

The below code shortens inputted url and display its bitly result but i want it to encode the result in base64 instead.

ie it would have shortened the inputted url to bitly in hidden but will display only the base64 encoded result.

For example, if a particular shortened url result is

http://bit.ly/url

it should display

aHR0cDovL2JpdC5seS91cmw=

jQuery

$(document).ready(function() {

  //bit_url function
  function bit_url(url) {
    var url=url;
    var username="username"; // bit.ly Api username
    var key="BitLy Key"; //bit.ly Api key
    $.ajax({
      url:"http://api.bit.ly/v3/shorten",
      data:{longUrl:url,apiKey:key,login:username},
      dataType:"jsonp",
      success:function(v) {
        var bit_url=v.data.url;
        $("#result").html('<a href="'+bit_url+'" target="_blank">'+bit_url+'</a>');
      }
    });
  }


  $("#short").click(function() {
    var url=$("#url").val();
    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var urltest=urlRegex.test(url);
    if(urltest) {
      bit_url(url);
    } else {
    alert("Bad URL");
    }
  });

});

HTML

Enter URL:
<input type="text" placeholder="http://"" name="url" id="url"/>
<input type="submit" id="short" value="Submit"/>
<div id="result"></div>

Would appreciate any help.

You should be able to use btoa() to encode the bit.ly urls. Something like this would work:

$(document).ready(function() {

  //bit_url function
  function bit_url(url) {
    var url=url;
    var username="username"; // bit.ly Api username
    var key="BitLy Key"; //bit.ly Api key
    $.ajax({
      url:"http://api.bit.ly/v3/shorten",
      data:{longUrl:url,apiKey:key,login:username},
      dataType:"jsonp",
      success:function(v) {
        var bit_url=v.data.url;
        var encodedUrl = btoa(bit_url);
        console.log(encodedUrl);
        $("#result").html('<a href="'+bit_url+'" target="_blank">'+bit_url+'</a>');
      }
    });
  }


  $("#short").click(function() {
    var url=$("#url").val();
    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var urltest=urlRegex.test(url);
    if(urltest) {
      bit_url(url);
    } else {
    alert("Bad URL");
    }
  });

});

More information on encoding and decoding base64 in JavaScript is available in the developer docs here: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

Hope that helps!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM