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);
});
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'm using a search-function for a documentation site which upon selection of search hit shows page with text highlighted (just as a pdf-reader or netbeans would do).
To achive the highlight i use javascript with:
function searchHighlight(searchTxt) {
var target = $('#page').html();
var re = new RegExp(searchTxt, 'gi');
target = target.replace(
re,
'<span class="high">' + searchTxt + '</span>'
);
$('#page').html(target);
}
Problem / Question:
Since page incudes images with filenames based on md5, some searches messes up the image src.
Searching on "1000" will distort the
<img src="53451000abababababa---.jpg"
to
<img src="5334<span class="hl">1000</span>abababab--.jpg">
Is it possible to solve this with regexp, somehow excluding anything anjcent to ".jpg"?
Or would it be possible to, before highligting replace the images with placeholders, and after replace revert back to src?
Example:
replace all <img *> with {{I-01}}, {{I-02}} etc and keep the real src in a var.
Do the replace above.
Revert back from {{I-01}} to the <img src=".."/>
DOM-manipulation is of course an option, but I figure this could be done with regexp somehow, however, my regexp skills are lacking badly.
UPDATE
This code works for me now:
function searchHighlight(searchTxt) {
var stack = new Array();
var stackPtr = 0;
var target = $('#page').html();
//pre
target = target.replace(/<img.+?>/gi,function(match) {
stack[stackPtr] = match;
return '{{im' + (stackPtr++) + '}}';
});
//replace
var re = new RegExp(searchTxt, 'gi');
target = target.replace(re,'<span class="high">' + searchTxt + '</span>');
//post
stackPtr = 0;
target = target.replace(/{{im.+?}}/gi,function(match) {
return stack[stackPtr++];
});
$('#page').html(target);
}
One approach would be to create an array of all possible valid search terms. Set the terms as .textContent of <span> elements within #page parent element.
At searchHighlight function check if searchTxt matches an element within array. If searchTxt matches an element of array, select span element using index of matched array element, toggle "high" .className at matched #page span element, else notify user that searchTxt does not match any valid search terms.
$(function() {
var words = [];
var input = $("input[type=text]");
var button = $("input[type=button][value=Search]");
var reset = $("input[type=button][value=Reset]");
var label = $("label");
var page = $("#page");
var contents = $("h1, p", page).contents()
.filter(function() {
return this.nodeType === 3 && /\w+/.test(this.nodeValue)
}).map(function(i, text) {
var span = text.nodeValue.split(/\s/).filter(Boolean)
.map(function(word, index) {
words.push(word);
return "<span>" + word + "</span> "
});
$(text.parentElement).find(text).replaceWith(span);
})
var spans = $("span", page);
button.on("click", function(event) {
spans.removeClass("high");
label.html("");
if (input.val().length && /\w+/.test(input.val())) {
var terms = input.val().match(/\w+/g);
var indexes = $.map(terms, function(term) {
var search = $.map(words, function(word, index) {
return word.toLowerCase().indexOf(term.toLowerCase()) > -1 && index
}).filter(Boolean);
return search
});
if (indexes.length) {
$.each(indexes, function(_, index) {
spans.eq(index).addClass("high")
})
} else {
label.html("Search term <em>" + input.val() + "</em> not found.");
}
}
});
reset.on("click", function(event) {
spans.removeClass("high");
input.val("");
label.html("");
})
})
.high {
background-color: #caf;
}
label em {
font-weight: bold;
background-color: darkorange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="button" value="Search" />
<input type="button" value="Reset" />
<label></label>
<div id="page" style="max-width:500px;border:1px solid #ccc;">
<h1 style="margin:0px;">test of replace</h1>
<p>After Luke comes to Dagobah, Yoda initially withholds his true identity. He’s trying to get a sense of who Luke is as a person; Yoda understands that there’s a lot at risk in training Luke to be a Jedi, especially considering what happened with his
father.
<img style="float:right;" width="200" src="http://a.dilcdn.com/bl/wp-content/uploads/sites/6/2013/11/04-400x225.jpg">And Yoda is not impressed — Luke is impatient and selfish. With “Adventure. Excitement. A Jedi craves not these things,” the Jedi Master makes clear that Luke must understand the significance and meaning of the journey he thinks he wants to make.
It’s an important lesson for Luke and for audiences, because when Luke faces Vader at the film’s climax, we see the stakes involved in the life of a Jedi</p>
<p>Now Yoda-search works, however a search on "sites" will break the image-link. (Yes, I know this implementation isn't perfect but I'm dealing with reality)</p>
</div>
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);
Trying to get the last part of the url in a pretty weird html structure. Don't ask why it's built that way. There is a very good reason behind it.
The html looks like this
<li class="lifilter"><input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js i'm trying to use
$('#Cheeks... label a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = url.split("/");
var finalvar = urlsplit[4];
$(this).addClass(finalvar);
});
edit: damn.. i can only post once every 90 minutes.
here is updated question with updated html
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js code i'm trying to use (from a previous answer)
$('.lifilter').each(function(){
$(this).find(".filtercheck").next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
OK, so it appears no one here attempted to try the solution here before posting.
First things first cheeks.... This is a tricky ID to find (You have to escape the periods). The label is also not part of the internal html where ID is cheeks..., so we need to find the adjacent element and look the a anchor tag you're looking for.
Here's the code:
$(document).ready(function() {
$('#Cheeks\\.\\.\\.').next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
And here is a working jsfiddle with the solution.
keeping it simple like your code you'd do
finalvar = urlsplit[urlsplit.length-1];
in case you don't want the base url as a valid return then:
finalvar = ( urlsplit.length > 1 ? urlsplit[urlsplit.length-1] : "" );
replace "" with your preferred error/default return
you could also try to find the index of the last '/' and do a substring.
try this.
FIDDLE DEMO
var URI = 'www.example.com/sub1/sub2/sub3/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
//RESULT : "sub3"
You can extract the last section of a path (i.e. everything after the last /) by using a regular expression:
text.replace(/.*\//g, "")
This will remove all of the text before a slash, as well as the slash itself. You'll also notice that your selector wasn't matching any elements; you're looking for labels nested within inputs, which doesn't match the html you posted (and isn't a valid DOM structure). An appropriate selector would be .lifilter label a, since the <label> is within the <li>.
$(function() {
setTimeout(function() {
$('.lifilter label a').each(function() {
// strip everything up to and including the last forward slash
var path = $(this).attr('href').replace(/.*\//g, "");
$(this).addClass(path);
});
}, 1500);
});
a.cheeks:after {
content: " (className = 'cheeks')";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
if you want the last section of url for example activation code or id.You can try this.
var url = 'www.abc.com/code=12345',
parts = url.split('='),
lastPart = parts.pop()
//lastPart = 12345