0

Looking over the Google Fonts API and couldn't find anything that would allow me to get the font names for each font from a normal font link like this one.

https://fonts.googleapis.com/css?family=Droid+Serif:400,700,700i|Merriweather:300,400,700,900i|Open+Sans+Condensed:300,300i,700

How can I get all the font names from a Google Webfonts URL?.

2 Answers2

1

It can be done using code like the following.

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var googleFontUrl = 'https://fonts.googleapis.com/css?family=Droid+Serif:400,700,700i|Merriweather:300,400,700,900i|Open+Sans+Condensed:300,300i,700';
var fontFamilies = getParameterByName('family', googleFontUrl).split('|');
var fontArr = [];
fontFamilies.forEach(function(item) {
  fontArr.push(item.split(':')[0]);
});

alert(fontArr.join(', '));

JSFiddle: https://jsfiddle.net/5qvpg606/

Explanation:

  1. First, retrieve value of the family parameter from the URL using the getParameterByName function. In this example, the value of the family parameter is "Droid Serif:400,700,700i|Merriweather:300,400,700,900i|Open Sans Condensed:300,300i,700"

  2. Then split the value into an array to get the font families. We use JS String .split() method with "|" as the separator. Now items in the array are: "Droid Serif:400,700,700i", "Merriweather:300,400,700,900i", and "Open+Sans Condensed:300".

  3. Loop through the array, split each item (string) using ":" as the separator, get the first part (which contains family name) and push it to fontArr, so you'll get an array that contains "Droid Serif", "Merriweather", and "Open Sans Condensed".

  4. To see the result, simply join the array: fontArr.join(', ')

icaru12
  • 1,522
  • 16
  • 21
  • Thank you for this, i'll try it out. Did you make this function or did you find it elsewhere? Would you mind explaining what's going on so I can understand it better? –  Aug 13 '16 at 03:44
  • 1
    I've added explanation. The `getParameterByName` function was taken from [here](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript). The rest is my idea. – icaru12 Aug 13 '16 at 05:35
-1
  1. Look: https://fonts.google.com/specimen/Open+Sans?selection.family=Open+Sans
  2. Then select the font to use it.
  3. Click: bottom right corner
  4. Look: Specify in CSS.

Done!

Derian André
  • 220
  • 3
  • 12
  • You misunderstood. I'm looking to do this dynamically with any fonts selected, using javascript. –  Aug 12 '16 at 02:55
  • I see, I don't know a lot of js but if you can get the font-name of the url and raplace + with space, you could use that. Usin = and : as delimiters. – Derian André Aug 12 '16 at 04:12