Search code examples
javascriptgoogle-webfonts

How do I pass font names to webfont.load as a string


I am using basic font loading like this:

WebFont.load({
    google: {
        families: [ 'Droid Sans','Cookie','Parisienne' ]
    }
});

But I need to pass the font names to this as a string. Something like:

var fntstr = "'Droid Sans','Cookie','Parisienne'";
WebFont.load({
    google: {
        families: [ fntstr ]
    }
});

Why doesn't this work? Isn't that just a json structure being passed to Webfont.load?


Solution

  • In your first example, families is an array containing 3 strings.

    ['Droid Sans','Cookie','Parisienne']
    

    In your second example, families is an array containing 1 string.

    ["'Droid Sans','Cookie','Parisienne'"]
    

    To make this work, you want to do something like the following:

    var fntstr = "'Droid Sans','Cookie','Parisienne'";
    var fntarr = fntstr.split(',');
    WebFont.load({
        google: {
            families: fntarr
        }
    });
    

    The split method will split your string at each comma and create an array with the elements.

    http://www.w3schools.com/jsref/jsref_split.asp