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>
Related
I have some simple code that allows you to enter Amazon isbns/asins and converts them to hyperlinks. These hyperlinks are Amazon.com searches for the said isbn/asin.
Example pic: http://imgur.com/a/rYgYt
Instead of the hyperlink being a search I would like the link to go directly to the products offer page.
The desired link would be as follows:
https://www.amazon.com/gp/offer-listing/ASIN/ref=dp_olp_used?ie=UTF8&condition=used
"ASIN" would be where the ASIN/ISBN would need to be populated to generate the link, for example:
Im asking if someone could help modify my existing code to create the change. My skills lack the ability to implement the change. The existing code is as follows:
<html>
<head>
</head>
<div><b>ISBN Hyperlinker</b></div> <textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea> <div><b>Hyperlinked text:</b></div> <div id="output" style="white-space: pre"></div>
<input type="button" id="button" Value="Open All"/>
<script>
var input = document.getElementById('numbers');
var button = document.getElementById('button');
var output = document.getElementById('output')
var base =
'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
var urls = []
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
button.addEventListener('click', openAllUrls, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
urls=[];
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item);
container.appendChild(link);
urls.push(base + item);//add the url to our array of urls for button click
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
function openAllUrls(){
for(var i=0; i< urls.length; i++){//loop through urls and open in new windows
window.open(urls[i]);
}
}
handler(); // run on load
</script>
</html>
to modify output URL, replace
var base = ".....';
with
var basePrefix = 'https://www.amazon.com/gp/offer-listing/';
var baseSuffix = '/ref=dp_olp_used?ie=UTF8&condition=used';
and replace
base + item
with
basePrefix + item + baseSuffix
I know there are many similar questions posted, and have tried a couple solutions, but would really appreciate some guidance with my specific issue.
I would like to remove the following HTML markup from my string for each item in my array:
<SPAN CLASS="KEYWORDSEARCHTERM"> </SPAN>
I have an array of json objects (printArray) with a printArray.header that might contain the HTML markup.
The header text is not always the same.
Below are 2 examples of what the printArray.header might look like:
<SPAN CLASS="KEYWORDSEARCHTERM">MOST EMPOWERED</SPAN> COMPANIES 2016
RECORD WINE PRICES AT <SPAN CLASS="KEYWORDSEARCHTERM">NEDBANK</SPAN> AUCTION
I would like the strip the HTML markup, leaving me with the following results:
MOST EMPOWERED COMPANIES 2016
RECORD WINE PRICES AT NEDBANK AUCTION
Here is my function:
var newHeaderString;
var printArrayWithExtract;
var summaryText;
this.setPrintItems = function(printArray) {
angular.forEach(printArray, function(printItem){
if (printItem.ArticleText === null) {
summaryText = '';
}
else {
summaryText = '... ' + printItem.ArticleText.substring(50, 210) + '...';
}
// Code to replace the HTML markup in printItem.header
// and return newHeaderString
printArrayWithExtract.push(
{
ArticleText: printItem.ArticleText,
Summary: summaryText,
Circulation: printItem.Circulation,
Headline: newHeaderString,
}
);
});
return printArrayWithExtract;
};
Try this function. It will remove all markup tags...
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
Call this function sending the html as a string. For example,
var str = '<SPAN CLASS="KEYWORDSEARCHTERM">MOST EMPOWERED</SPAN> COMPANIES 2016';
var expectedText = strip(str);
Here you find your expected text.
It can be done using regular expressions, see below:
var s1 = '<SPAN CLASS="KEYWORDSEARCHTERM">MOST EMPOWERED</SPAN> COMPANIES 2016';
var s2 = 'RECORD WINE PRICES AT <SPAN CLASS="KEYWORDSEARCHTERM">NEDBANK</SPAN> AUCTION';
function removeSpanInText(s) {
return s.replace(/<\/?SPAN[^>]*>/gi, "");
}
$("#x1").text(removeSpanInText(s1));
$("#x2").text(removeSpanInText(s2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1 ->
<span id="x1"></span>
<br/>2 ->
<span id="x2"></span>
For more info, see e.g. Javascript Regex Replace HTML Tags.
And jQuery is not needed, just used here to show the output.
I used this little replace function:
if (printItem.Headline === null) {
headlineText = '';
}
else {
var str = printItem.Headline;
var rem1 = str.replace('<SPAN CLASS="KEYWORDSEARCHTERM">', '');
var rem2 = rem1.replace('</SPAN>', '');
var newHeaderString = rem2;
}
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);
I want to create links, based on a specific format.
When I type this:
google->apple
I want get get this link:
https://www.google.hu/search?q=apple
I tried this way, but unfortunately it is not working:
//Intelligent actions start
function replace(){
var str = $('.smile').html();
var re = /google->([^ \n$]+)/g;
var url = "https://www.google.hu/search?q=" + re.exec(str)[1];
}
//Intelligent actions end
Update
Based #vinayakj answer, I start create a solution for this:
//Intelligent actions start
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
//location.href = url;
}
$( document ).ready(function() {
googleSearch($('.comment-content p').text())
$( ".comment-content p" ).replaceWith( "<a href='url'>url</a>" );
});
//Intelligent actions end
And looks like replacewith function reaplce all content in
.comment-content p
with:
url
And this function it has some problem:
Reaplce all text even if dosen't find this sting in div:
google-->some word
The link is absolute incorrect becouse I get back this value everywhere:
url
What am I doing wrong?
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
location.href = url;
}
<input onchange="googleSearch(this.value)" type=text>
Here is the final solution after all your comments
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
var url = urls[parts[0]].replace("#",encodeURI(parts[1]));
return = $("<a/>",{href: url, class:parts[0]+"-search"}).text("Keresés ..."+parts[1]);
}
$(function() {
$("div.comment-content > p.smile").each(function() {
var $link = getLink($(this).text());
$(this).html($link);
});
});
Old answer
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
return urls[parts[0]].replace("#",parts[1]);
}
window.onload=function() {
document.getElementById("myForm").onsubmit=function() {
var str = document.getElementById("q").value;
var url = getUrl(str);
if (url) alert(url); // location.href=url;
return false; // cancel the submit
}
}
<form id="myForm">
<input id="q" type="text">
</form>
I found the solution, but thanks for everybody:
$("div.comment-content > p.smile").each(function(){
var original = $(this).text();
var replaced = original.replace(/google->([^.\n$]+)/gi, '<a class="google-search" href="https://www.google.hu/search?q=$1" target="_blank">Keresés a googleben erre: $1</a>' );
$(this).html(replaced);
console.log("replaced: "+replaced);
});
$("a.google-search").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});
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>