I am using Autolinker.js to linkify text inputted from a form, but I would like to exclude example.com from being linked.
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = Autolinker.link(formInput);
naturally yields linkedText having both urls linkified. I tried changing the url options using
var options = {urls: { schemeMatches: true, wwwMatches: true, tldMatches: false }};
var linkedText = Autolinker.link(formInput, options);
but this eliminates the link on google.com as well as the example.com while leaving www.kbb.com linked.
Basically I just want to exclude a single specific url, namely example.com, from being linked.
Sorry that I just noticed this thread. I'm the library author. I know it's pretty late but leaving this reply for anyone else who comes across it.
The easiest way to exclude a particular url from being autolinked is to leverage the replaceFn option. For example:
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = Autolinker.link( formInput, {
replaceFn: function( match ) {
if( match.getType() === 'url' ) {
var url = match.getUrl();
if( url.indexOf( 'example.com' ) !== -1 ) {
return false; // don't autolink matches for example.com
}
}
return true; // autolink everything else as usual
}
} );
This produces the result of:
Don't link example.com but link google.com and kbb.com please
Here is some documentation on the methods that can be called on UrlMatch objects: http://greg-jacobs.com/Autolinker.js/api/#!/api/Autolinker.match.Url
And a more in-depth example of using replaceFn: https://github.com/gregjacobs/Autolinker.js#custom-replacement-function
Replace text with a token, run autolink, replace token with original text. The obvious weakness here is that if formInput contained ||anything|| it would break.
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var stuffIdontwanttolink = ['example.com', 'google.com'];
stuffIdontwanttolink.forEach(function(entry, index) {
formInput = formInput.replace(entry, '||' + index + '||');
});
console.log(formInput);
//var linkedText = Autolinker.link(formInput);
var linkedText = "Don't link ||0|| but link ||1|| and <a href='//www.kbb.com'>www.kbb.com</a> please"; // Simulated
stuffIdontwanttolink.forEach(function(entry, index) {
linkedText = linkedText.replace('||' + index + '||', entry);
});
console.log(linkedText);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
So I wrote a function to wrap the Autolinker in:
function excludedLinkify (inputText) {
var exclusions = [
{url:'example.com', temp:'7g578v43gc7n3744c'}
];
$.each(exclusions, function (i, e) {
inputText = inputText.replace(e.url, e.temp);
});
inputText = Autolinker.link(inputText);
$.each(exclusions, function (i, e) {
inputText = inputText.replace(e.temp, e.url);
});
return inputText;
}
So that to achieve the desired result I can now
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = excludedLinkify(formInput);
Related
I have function, which shows / outputs the urls from the textarea. At the moment however it won't merge duplicates into 1 URL. How can I output same urls as one (Merge http://google.com, www.google.com, http://www.google.com, or just google.com)?
At the moment:
Should be:
My Code:
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/[^\s]+)/g;
$("#textarea").val().replace(urlRegex, function(url) {
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea>
<div id="converted_url"></div>
JS FIDDLE
Credits
Scott Marcus, Stackoverflow
Simple fix: store matched urls in array and append link only if url is not present in that array.
UPDATE: changed regex to /((https?:\/\/|www\.|\/\/)[^\s]+)/g so it matches links starting with http://, https://, www., //. You may use any other regex covering other cases (like http://www.) just modify stored url so that you'll be able to compare it (you may want to treat http and https link as unique).
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /((https?:\/\/|www\.|\/\/)[^\s]+)/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
let trimmedUrl = url.replace(/^(https?:\/\/|www\.|\/\/)/, "");
if (found.includes(trimmedUrl)) {
return;
}
found.push(trimmedUrl);
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
var link = "";
var protOmmitedURL = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
if (found.includes(protOmmitedURL)) {
return;
}else
{
link = '<div>' + url + '</div>';
found.push(protOmmitedURL);
}
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
I'd like to loop through list items onload and detect whether or not they have a YouTube URL and use the video id from the URL in an iframe. This is what I've done so far but it's not working:
$('li').each(function() {
var url = $(this).text();
if (url != undefined || url != '') {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
// Do anything for being valid
// if need to change the url to embed url then use below line
$(this).find('.videoObject').attr('src', 'https://www.youtube.com/embed/' + match[2] + '?autoplay=0&enablejsapi=1').show();
} else {
// Do anything for not being valid
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
foo
<iframe class="videoObject" src=""></iframe>
</li>
<li>
bar
<iframe class="videoObject" src=""></iframe>
</li>
<li>
foo https://www.youtube.com/watch?v=Vr3ya_uPmxg
<iframe class="videoObject" src=""></iframe>
</li>
</ul>
jsFiddle
I prefer you to create virtual A element, then you get access to some helpful DOM methods to parse it's href value like hostname, protocol, pathname, search, hash, etc. Then it's easier to validate the url parts. I wrote a small function, it returns:
false if the URL is not youtube url,
empty string if it is youtube url but without video ID
string id.
var links =
['https://youtube.com/watch?v=01jcwGApTWA',
'https://youtube.com/watch?v=01jcwGApTWA&t',
'https://youtu.be/01jcwGApTWA?t=31',
'https://www.youtube.com/watch?v=Ujqdle7CvIU&spfreload=10',
'https://www.youtube.com/watch?v=nQ9ww9E_1C4',
'https://www.youtube.com/embed/nQ9ww9E_1C4',
'https://www.youtube.com/embed/nQ9ww9E_1C4?autoplay=1',
'https://www.youtube.com/embed/nQ9ww9E_1C4?playlist=XGSy3_Czz8k&loop=1',
'https://www.youtube.com',
'http://anothersite.com'];
function isYoutube(getURL){
if(typeof getURL!=='string') return false;
var newA = document.createElement('A');
newA.href = getURL;
var host = newA.hostname;
var srch = newA.search;
var path = newA.pathname;
if(host.search(/youtube\.com|youtu\.be/)===-1) return false;
if(host.search(/youtu\.be/)!==-1) return path.slice(1);
if(path.search(/embed/)!==-1) return /embed\/([A-z0-9]+)(\&|$)/.exec(path)[1];
var getId = /v=([A-z0-9]+)(\&|$)/.exec(srch);
if(host.search(/youtube\.com/)!==-1) return !getId ? '':getId[1];
}
console.log(isYoutube(links[0]));
console.log(isYoutube(links[1]));
console.log(isYoutube(links[2]));
console.log(isYoutube(links[3]));
console.log(isYoutube(links[4]));
console.log(isYoutube(links[5]));
console.log(isYoutube(links[6]));
console.log(isYoutube(links[7]));
console.log(isYoutube(links[8]));
console.log(isYoutube(links[9]));
I have a number of pages that contain phone number in this format xxx-xxx-xxxx.
These phone numbers are not links, what I need to do it write some script that first finds these phone numbers. This is what I have got for that:
$(document).ready(function(){
var content = $(".main").text();
var phoneNumber = content.match(/\d{3}-\d{3}-\d{4}/)
alert(phoneNumber);
});
This works in so much that is captures the number, what I need to do now is replace that phone number on the page with
'' + 'originalPhoneNumber' + ''
However I am totally lost at this point. Can I use .replaceWith() in jQuery?
EDIT:
Okay I tried to modify the code to include the second attribute i wanted:
$(document).ready(function () {
var content = $(".main").html();
content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){
return $('<a>').attr({
href: "tel:"+v,
onclick: "ga('send', 'event', 'lead', 'phone call', 'call');"
}).html(v)[0].outerHTML;
});
$('.main').html(content);
});
It is still adding the href but it is ignoring the onclick.
This will replace all matching strings in an element with a tel: link
<div class = "main">333-333-3333 444-444-4444</div>
<script type="text/javascript">
var content = $(".main").text();
content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){
return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html();
});
$('.main').html(content);
</script>
Or more neatly implemented as :
$.fn.extend({
tel : function(def) {
var set = {
regex : /\d{3}-\d{3}-\d{4}/g,
classname : ""
}
$.extend(true, set, def);
var c = $(this).html();
c = c.replace(set.regex, function(v){
return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html();
});
$(this).html(c);
return this;
}
});
// default regex: 000-000-0000
$('.main').tel();
// default regex: 000-000-0000 <a> class of tel-link applied
$('.main').tel({ classname : "tel-link" });
// override regex: 0000-0000-000
$('.main').tel({ regex: /\d{4}-\d{4}-\d{3}/g });
Previous stackoverflow
This jquery statement will look for domain.com and append ?parameter to the end of the URL. It will NOT append if ?parameter has already been added.
The problem: My current jquery modifies all URLs and not domain.com. Here is the regex statement that i would like to use and is tested to work. However, when implemented, nothing is appended. Any help is greatly appreciated!
Regex i would like to use:
\b(https?://)?([a-z0-9-]+\.)*domain\.com(/[^\s]*)?
RegexFiddle
JSFiddle for convience
Code to be modified
<div id="wp-content-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content"><a title="Link to test domain" href="http://www.domain.com">Link to google</a>
<a href="http://www.google.com/directory/subdirectory/index.html">This is another link</a>
<a href="http://domain.com/directory/index.html">This is a 3rd link</a>
<a href="http://www.domain.com/subdir?parameter">this url already has parameters</a></textarea></div>
current jquery statement
var url = 'www.domain.com';
var append = '?parameter';
$(".wp-editor-area").each(function() {
$(this).text(urlify($(this).text()));
});
function urlify(text) {
var urlRegex = /(\b(https?|ftp|file):\/\/[www.domain.com][-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
// if the url does not contain append, concat append to the URL
if (url.indexOf(append) == -1) {
return url + append;
}
return url;
});
}
Current output
<a title="Link to test domain" href="http://www.domain.com?parameter">Link to google</a>
This is another link
This is a 3rd link
Test this code - it should be what you need (or at least starting point) >>
function urlify(text) {
var append = '?parameter';
text = text.replace(/("(?:(?:https?|ftp|file):\/\/)?(?:www.|)domain.com(?:\/[-a-z\d_.]+)*)(\?[^"]*|)(")/ig,
function(m, m1, m2, m3) {
return ((m1.length != 0) && (m2.length == 0)) ? m1 + append + m3 : m;
});
return text;
}
$(".wp-editor-area").each(function() {
this.innerHTML = urlify(this.innerHTML);
});
I have a url variable http://blah.com/blah/blah/blah and I have another url http://shop.blah.com/ I want to take the first url (blah.com) and add the ending blah/blah/blah to the second url http://shop.blah.com
So I end up with http://shop.blah.com/blah/blah/blah
Any idea of how I could do this?
var url1 = 'http://blah.com/blah/blah/blah';
var url2 = 'http://shop.blah.com/';
var newUrl = url2 + url1.replace(/^.+?\..+?\//, '');
It sounds like the jQuery-URL-Parser plugin might come in handy here:
var url = $.url(); //retrieves current url
You can also get specific parts of the URL like this:
var file = $.url.attr("file");
var path = $.url.attr("path");
var host = $.url.attr("host");
...
If you need to get Querystring parameters:
var parm = $.url.param("id");
If the intent is just to add shop to the front of the domain name:
var url2 = url1.replace('://', '://shop.');
<script>
$(document).ready(function(){
//this uses the browser to create an anchor
var blah = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
blah.href = "http://blah.com/blah/blah/blah?moreBlah=helloWorld#hashMark";
var shop = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
shop.href = "http://shop.blah.com/";
shop.pathname = blah.pathname; //the blahs
shop.search = blah.search; //the blah query
shop.hash = blah.hash; // the blah hashMark
alert("These are the droids you're looking for: "+shop.href);
});
</script>