Search code examples
javascriptstringprototype

Pass arguments to string.prototype extension in javascript


I use string.prototype to linkify text passages on my website. On some sites I want to add different notes and thus want to pass an additional argument to linkify.

My initial idea was to do it as follows.

function linkifyText() {
    
    var uglyLinksPattern = /\[(.*?)\]/gim; // match all letters between square brackets
                
    if(!String.linkify) {
        String.prototype.linkify = function(note) {
            var textInput = this;    
            return textInput.replace(uglyLinksPattern, '<a target="_blank" rel="noopener nofollow" href="$&">$&</a>' + note);            
        }
    }
    return uglyLinksPattern
}
        
function linkifyDialogue (text) {    
    linkifyText();
    var note = 'Ad';        
    var linkedText = String.linkify.call(text, note);
    $('#textElem').html(linkedText);        
}

I found some tutorials using call and apply. However, I wasn't able to transfer it to my case and hope to get an answer on how to pass an argument to the string.prototype property. So what is the trick?


Solution

  • The way you've tried to implement it is kinda weird (no offense intended). You could've made this much simpler. See:

    //Do this just once
    String.prototype.linkify=function(note) {
        return this.replace(/\[(.*?)\]/gim,"<a target='_blank' rel='noopener nofollow' href='$1'>$1</a>"+note);
    };
    
    function linkifyDialogue(text) {    
        var note="Ad",        
            linkedText=text.linkify(note);
        $('#textElem').html(linkedText);        
    }
    

    All strings are objects already. If you add a method to the prototype, there's no need to use call() or apply() unless you actually need to (i.e. to call it with a different value for this, pass an array of values as different parameters, etc.).