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?
String.linkify(static method) orString.prototype.linkify?ifthen.var textInput = thiswhen you could just usethis.replaceinstead. Also given that it's 2020 why notconst uglyLinksPattern? Try and useletandconstinstead ofvar.textInputwas for better readability.