Javascript - How to remove link within links - javascript

Let's say a string contains http://google.com. When I linkify the whole string (that has both unlinked URLs and linked URLs, like the one shown above), it will become http://google.com">http://google.com</a>.
Is there a way to revert the incorrect links (which are the ones already linked before linkifying) back to http://google.com?
I found in WordPress, that it uses $ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret); (in wp-includes/formatting.php) to accomplish this. Can someone help me to do this in JavaScript?

Have a look at this http://jsfiddle.net/mplungjan/V5Qca/
<script>
function linkify(id,URL) {
var container = document.getElementById(id);
var links = container.getElementsByTagName("a");
if (links.length ==0) {
container.innerHTML=container.innerHTML.link(URL);
return;
}
var nodes = container.childNodes;
for (var i=nodes.length-1;i>=0;--i) {
if (nodes[i].nodeType ==3 && nodes[i].parentNode.nodeName!="A") {
var link = document.createElement("a");
link.href=URL;
link.innerHTML=nodes[i].nodeValue;
container.replaceChild(link, nodes[i]);
}
}
}
window.onload=function() {
linkify("div1","http://www.google.com/");
}
</script>
<div id="div1">
this is a test of replacing text with links with linkified content
</div>

Related

Trying to figure out how to create links using createTextNode

First off I would like to say, the person that originally created this portion of the code is no longer on the team.
We are creating a development tool to Administrate and Develop servers for our game, that has its own programming language.
I'm using JavaFX with WebView to generate the chat area of the development tool to communicate with other developers and staff. However I want it so hen you post a link it actually shows as a link instead of plain text. I have tried things such as AutoLinker with no success. Here is the HTML portion of the webview.
<script src=".././scripts/Autolinker.js"></script>
<script type="text/javascript">
app = null;
const messages = document.getElementById("messages");
function addMessage(message, options) {
const p = document.createElement("p");
const c = message.indexOf(":");
const modifiedMessage = message; //replaceURLWithHTMLLinks(message);
const ridBrackets = options.replace(/[\[\]']/g, "");
const tokenize = ridBrackets.split(",", 2);
const rcChatOptions = tokenize;
const mFontColor = tokenize[rcChatOptions.BFONTCOLOR];
let timeStampFormat = tokenize[rcChatOptions.TIMESTAMP];
if(c > -1) {
const u = document.createElement("span");
const a = document.createElement("a");
u.className = "user";
if(mFontColor != null) {
u.style.color = mFontColor;
} else {
u.style.color = "#00c02b";
}
//Turn plain text links into actual links
u.appendChild(document.createTextNode(Autolinker.link(modifiedMessage.substring(0, c + 1))));
p.appendChild(u);
if(document.selectedfont != null) {
p.style.fontFamily = document.selectedfont;
}
p.appendChild(document.createTextNode(modifiedMessage.substring(c + 1)));
} else {
p.appendChild(document.createTextNode(modifiedMessage));
}
// Append message and scroll to bottom (if at bottom)
const scrollTop = document.body.scrollTop;
const scrolledToBottom = scrollTop + window.innerHeight >= document.body.scrollHeight;
if(scrolledToBottom) {
messages.appendChild(p);
window.scrollTo(document.body.scrollLeft, document.body.scrollHeight - window.innerHeight);
} else {
messages.appendChild(p);
}
messages.style.backgroundColor = "transparent";
}
</script>
I removed portions of the code that I felt was just a distraction.
This what the tool looks like
https://share.getcloudapp.com/kpuNDB4m
this is what it looks like using AutoLinker
https://share.getcloudapp.com/8LunomDL
(So auto linker is doing its job, it just still isn't rending as HyperLinks)
It looks like the TextNode is created after collecting some substring which would be the link. Here's an example of what it would look like if a link was created directly in js then passed to the TextNode.
One thing you can do is place the text inside of an a tag within a paragraph and then convert like so:
var link = document.createElement('link');
link.innerHTML = 'Website: <a href="http://somelink.com" </a>
link.href = 'http://somelink.com';
link.appendChild(document.createTextNode('http://somelink.com'));
After getting pointed in the right direction (By Frank, Thank You) I found a javascript Library that helped me accomplish what I was looking for.
Library
https://github.com/cferdinandi/saferInnerHTML
Here is an example!
https://share.getcloudapp.com/nOuDPnlp
Usage:
saferInnerHTML(message, modifiedMessage, true);
The last param is an option, append or overwrite.
Obviously, I will have to do some CSS work to make them not display as buttons. But it is exactly what I was trying to achieve.

Replacing iframe source with Javascript - Can I use a loop?

I have a list of items (districts) on a page, and an iframe pulling in a map on the same page. When a user clicks on one of the districts, the JavaScript changes the source of the iframe to show a map of the district the user clicked.
My current code simply uses an "onclick" for each district, which then calls a function to change the source of the iframe.
I am wondering if I can simplify this code at all, possibly by using a loop? If I have 15 more districts to add to the page, will I have to add another "onclick" and another function for each one? Or is there an easier way that I am missing?
Simplified HTML:
<div id="districtlist">
Allen
Barren
Butler
<!--about 15 more links to follow-->
</div>
<iframe id="maparea" src="http://www.reddit.com"></iframe>
Javascript:
var a = document.getElementById("districtlist")
a.getElementsByTagName("a")[0].onclick = Allen;
a.getElementsByTagName("a")[1].onclick = Barren;
a.getElementsByTagName("a")[1].onclick = Butler;
//more lines...
function Allen() {
document.getElementById("maparea").src="http://www.youtube.com";
}
function Barren() {
document.getElementById("maparea").src="http://www.mentalfloss.com";
}
function Butler() {
document.getElementById("maparea").src="http://www.amazon.com";
}
//more functions...
I believe you could try this
var elems = document.getElementById("districtlist").querySelectorAll('a');
[].forEach.call(elems, function(elem) {
elem.onclick = function() {
var url = '';
switch(elem.innerText) {
case 'Allen':
url = "http://www.mentalfloss.com";
break;
case 'Barren':
url = "http://www.mentalfloss.com"
break;
case 'Butler':
url = "http://www.amazon.com";
break;
}
document.getElementById("maparea").src=url;
}
});

Javascript pulling content from commented html

Bit of a JS newbie, I have a tracking script that reads the meta data of the page and places the right scripts on that page using this:
var element = document.querySelector('meta[name="tracking-title"]');
var content = element && element.getAttribute("content");
console.log(content)
This obviously posts the correct tag to console so I can make sure it's working .. and it does in a test situation. However, on the actual website the meta data i'm targeting is produced on the page by a Java application and beyond my control, the problem is it is in a commented out area. This script cannot read within a commented out area. ie
<!-- your tracking meta is here
<meta name="tracking-title" content="this-is-the-first-page">
Tracking finished -->
Any ideas appreciated.
You can use this code:
var html = document.querySelector('html');
var content;
function traverse(node) {
if (node.nodeType == 8) { // comment
var text = node.textContent.replace(/<!--|-->/g, '');
var frag = document.createDocumentFragment();
var div = document.createElement('div');
frag.appendChild(div);
div.innerHTML = text;
var element = div.querySelector('meta[name="tracking-title"]');
if (element) {
content = element.getAttribute("content");
}
}
var children = node.childNodes;
if (children.length) {
for (var i = 0; i < children.length; i++) {
traverse(children[i]);
}
}
}
traverse(html);
One way is to use a NodeIterator and get comment nodes. Quick example below. You will still need to parse the returned value for the data you want but I am sure you can extend this here to do what you want.
Fiddle: http://jsfiddle.net/AtheistP3ace/gfu791c5/
var commentedOutHTml = [];
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT, NodeFilter.FILTER_ACCEPT, false);
var currentNode;
while (currentNode = iterator.nextNode()) {
commentedOutHTml.push(currentNode.nodeValue);
}
alert(commentedOutHTml.toString());
You can try this. This will require you to use jQuery however.
$(function() {
$("*").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});

Google Apps Script - Move Cursor onclick

I would like to implement a Table of Contents in the sidebar of a Google Docs document which will take you to the appropriate sections when clicked. I am generating the HTML for the sidebar element by element, and I see that there is a moveCursor(position) function in Document class, but I can't see how to actually call it using onclick. Not the full code but shows the problem:
function generateHtml() {
var html = HtmlService.createHtmlOutput('<html><body>');
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
//Iterate each document element
var totalElements = body.getNumChildren();
for(var i = 0; i < totalElements; ++i) {
var element = body.getChild(i);
if(element.getType() == DocumentApp.ElementType.PARAGRAPH) {
var text = paragraph.getText();
if(text.trim()) { //Not blank paragraph
var position = document.newPosition(element, 0);
/**Would like to have <a onclick=document.moveCursor(position)> here**/
//Show first 20 chars as preview in table of contents
html.append('Detected paragraph ')
.append(text.substring(0, 20))
.append('<br />');
}
}
}
html.append('</body></html>');
return html;
}
How can I accomplish this in Apps Script? The code can be completely restructured as needed.
This line:
/**Would like to have <a onclick=document.moveCursor(position)> here**/
Change to:
<div onmouseup="myClientFunction()">Text Here</div>
Add a <script> tag to your HTML:
<script>
var valueToSend = code to get value;
window.myClientFunction = function() {
google.script.run
.myGsFunctionToMoveCursor(valueToSend);
};
</script>
Then you need a myGsFunctionToMoveCursor() function in a script file (.gs extension)
function myGsFunctionToMoveCursor(valueReceived) {
//To Do - Write code to move cursor in Google Doc
. . . Code to move cursor
};

Google news box within div

I'm trying to place a google news search within a div on my site. I'm currently using the script google provides, but am a novice at Ajax/JavaScript. I am able to display the most recent stories from google news, but don't know how to have it display within a div let alone manipulate the style with CSS. Below is the code I'm using. Any help would be greatly appreciated!
<script type="text/javascript">
google.load('search', '1');
var newsSearch;
function searchComplete() {
// Check that we got results
document.getElementById('averagecontainer').innerHTML = '';
if (newsSearch.results && newsSearch.results.length > 0) {
for (var i = 0; i < newsSearch.results.length; i++) {
// Create HTML elements for search results
var p = document.createElement('p');
var a = document.createElement('a');
a.href = newsSearch.results[i].url;
a.innerHTML = newsSearch.results[i].title;
// Append search results to the HTML nodes
p.appendChild(a);
document.body.appendChild(p);
}
}
}
function onLoad() {
// Create a News Search instance.
newsSearch = new google.search.NewsSearch();
// Set searchComplete as the callback function when a search is
// complete. The newsSearch object will have results in it.
newsSearch.setSearchCompleteCallback(this, searchComplete, null);
// Specify search quer(ies)
newsSearch.execute('Barack Obama');
// Include the required Google branding
google.search.Search.getBranding('branding');
}
// Set a callback to call your code when the page loads
google.setOnLoadCallback(onLoad);
</script>
If I understand correctly, this is what you need:
Create the <div> and give it an ID:
<div id="your-div">HERE BE NEWS</div>
Then modify the searchComplete funcion like this:
function searchComplete() {
var container = document.getElementById('your-div');
container.innerHTML = '';
if (newsSearch.results && newsSearch.results.length > 0) {
for (var i = 0; i < newsSearch.results.length; i++) {
// Create HTML elements for search results
var p = document.createElement('p');
var a = document.createElement('a');
a.href = newsSearch.results[i].url;
a.innerHTML = newsSearch.results[i].title;
// Append search results to the HTML nodes
p.appendChild(a);
container.appendChild(p);
}
}
}
As for style manipulation, you can match the elements by the given ID in css. For example like this:
#your-div a {
font-weight: bold;
}
EDIT:
To show you that this is working, I have created a jsfiddle: http://jsfiddle.net/enjkG/
There is not a lot of things you can mess up here. I think you may have a syntactic error and did not check the console for errors.

Categories

Resources