gregjacobs / Autolinker.js

Utility to Automatically Link URLs, Email Addresses, Phone Numbers, Twitter handles, and Hashtags in a given block of text/HTML
MIT License
1.48k stars 238 forks source link

Custom Replacement of Links Example Code Not Working Verbatim #213

Closed julesforrest closed 7 years ago

julesforrest commented 7 years ago

var linkedText = Autolinker.link( input, {
    replaceFn : function( match ) {
        console.log( "href = ", match.getAnchorHref() );
        console.log( "text = ", match.getAnchorText() );

        switch( match.getType() ) {
            case 'url' :
                console.log( "url: ", match.getUrl() );

                if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) {
                    var tag = match.buildTag();  // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes
                    tag.setAttr( 'rel', 'nofollow' );
                    tag.addClass( 'external-link' );

                    return tag;

                } else {
                    return true;  // let Autolinker perform its normal anchor tag replacement
                }

            case 'email' :
                var email = match.getEmail();
                console.log( "email: ", email );

                if( email === "my@own.address" ) {
                    return false;  // don't auto-link this particular email address; leave as-is
                } else {
                    return;  // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`)
                }

            case 'phone' :
                var phoneNumber = match.getPhoneNumber();
                console.log( phoneNumber );

                return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>';

            case 'hashtag' :
                var hashtag = match.getHashtag();
                console.log( hashtag );

                return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>';

            case 'mention' :
                var mention = match.getMention();
                console.log( mention );

                return '<a href="http://newplace.to.link.mention.to/">' + mention + '</a>';
        }
    }
} );

This code from the docs doesn't catch any hashtags or mentions. Should I be specifying Twitter somewhere before this runs?

julesforrest commented 7 years ago

I found that if I added

mention: 'twitter',
hashtag: 'twitter',

before the replaceFn : function( match ) { it works fine.