How do I remove `<code></code>` from `<pre></pre>` with javascript? - javascript

The triple backticks in markdown render as <pre><code class="...">...</code></pre>. More specifically,
# in markdown
```java
```
# render as
<pre>
<code class="java">
...
</code>
</pre>
# my expecting result (for Google code prettify):
<pre class="prettyprint linenums lang-java">
...
</pre>
My current solution is to add the following code but it doesn't work.
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=son-of-obsidian></script>
<script type="text/javascript">
jQuery(document).ready(function () {
$('pre code').each(function() {
var code = $(this).html();
var lang = $(this).attr('class');
if (lang) {
$(this).parent().attr('class', 'prettyprint linenums lang-'+lang).html(code);
}
});
prettyPrint();
});
</script>
How do I remove <code class="...">...</code>?
I used SyntaxHighlighter <pre class="brush: java">...</pre> to highlighter my code blocks in WordPress + Windows Live Writer + PreCode(based on SyntaxHighlighter).
Currently, I turn to markdown. To insert a code blocks in markdown, I use
```java
code here
```
# OR
<pre class="brush: java">
code here
</pre>
Both of them doesn't work for me, because SyntaxHighlighter requires all left angle brackets inside <pre></pre> should be HTML entries escaped.
Therefore, I install Google code prettify but encounter the above issue (incompatiable).

Try the below out and let me know if this works for you.
$('pre').each(function() {
var el = $(this).find('code');
var code = el.html();
var lang = el.attr('class');
if (lang) {
$(this).addClass('prettyprint linenums lang-' + lang).html(code);
}
});
JSFiddle Demo

You are forgetting to remove the original code object from the pre element, causing the code to be duplicated. You should call $(this).remove(); to remove the old code object.

Related

Highlight code with Markdown-it.js and Highlight.js

In the current example, a Markdown snippet is ported to HTML and the output is shown in the DIV (ID Content).
The highlight function (hljs.highlight) is set to the options markdown-it (md). However, this is not carried out.
What do I have to change so that the output uses the highlight.js?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release#10.2.1/build/styles/default.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/11.0.1/markdown-it.min.js "></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.1/highlight.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
var md = window.markdownit();
md.set({
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre class="hljs"><code>' +
hljs.highlight(lang, str, true).value +
'</code></pre>';
} catch (__) {}
}
return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
}
});
var result = md.render('# markdown-it rulezz! \n\n```html <pre><code class="js">function test();</code></pre>```');
document.getElementById('content').innerHTML = result;
</script>
</body>
</html>
Hope it's not too late.
You must break line (\n) after your fenced code block.
So this:
var result = md.render('# markdown-it rulezz! \n\n```html <pre><code class="js">function test();</code></pre>```');
Should be:
var result = md.render('# markdown-it rulezz! \n\n ```html \n <pre><code class="js">function test();</code></pre>\n```');
This is how everything should be:
the .js files should be:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/11.0.1/markdown-it.min.js "></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.1/highlight.min.js"></script>
These are okay.
As for the .css, you can use the one you are using or you can use the one that is in the npm:
npm install markdown-it-highlight
get the .css file at node_modules/markdown-it-highlight/dist/index.css, that has nicer syntax highlighting color and use that.
Then you would have to set this defaults object and set this on the defaults.highlight:
var defaults = {
html: false, // Enable HTML tags in source
xhtmlOut: false, // Use '/' to close single tags (<br />)
breaks: false, // Convert '\n' in paragraphs into <br>
langPrefix: 'language-', // CSS language prefix for fenced blocks
linkify: true, // autoconvert URL-like texts to links
typographer: true, // Enable smartypants and other sweet transforms
// options below are for demo only
_highlight: true, // <= THIS IS WHAT YOU NEED
_strict: false,
_view: 'html' // html / src / debug
};
// and then do this:
defaults.highlight = function (str, lang) {
var esc = md.utils.escapeHtml;
console.log(str)
console.log(lang)
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre class="hljs"><code>' +
hljs.highlight(lang, str, true).value +
'</code></pre>';
} catch (__) {}
}else{
return '<pre class="hljs"><code>' + esc(str) + '</code></pre>';
}
};
// now set the md:
md = window.markdownit(defaults);
// now this is where you forgot the line break after the fenced code block:
const result = md.render('# markdown-it rulezz! \n ```html \n <pre><code class="js">function test();</code></pre>\n```');
document.querySelector('#content').innerHTML = result;
I outlined a few of the steps needed to get code highlighting working here: https://github.com/microsoft/AdaptiveCards/discussions/8081#discussioncomment-4219420
Summary:
Easy Way
First, make sure you support Markdown in cards:
import MarkdownIt from 'markdown-it'
// For Markdown in Adaptive Cards.
window.markdownit = MarkdownIt
Now we'll use another library to color code:
import highlight from 'highlight.js'
import 'highlight.js/styles/github.css'
Run:
highlight.highlightAll()
to update all your cards.
If you run it twice, then it will try to update cards that it already updated, and you'll get warnings. See https://github.com/microsoft/AdaptiveCards/discussions/8081#discussioncomment-4219420 for handling dynamically added cards.

How to display result of javascript as HTML link?

I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click

RegEx How to avoid automatically closing HTML tags

HTML:
<pre class="html">
List<String> list = Arrays.asList(str);
</pre>
JS:
var symbols = /(<|>|{|})/gi;
$('.html').each(function() {
var abc = $(this).html().replace(symbols, "<span class='blue'>$1</span>");
$(this).html(abc);
}
Output: (I am able to change the color of <,>)
List<string> list = Arrays.asList(str);
</string>
Its automatically appending
</string> at the end
and changing String to string (First letter capital to small)
Can anybody please help me how to fix this issue.
Don't do this:
<pre class="html">
List<String> list = Arrays.asList(str);
</pre>
Escape your brackets:
<pre class="html">
List<String> list = Arrays.asList(str);
</pre>
An alternative way would be to put your code in a script tag to avoid it being interpreted as an HTML tag:
<script type="template" id="code">
List<String> list = Arrays.asList(str);
</script>
<div id="output"></div>
var symbols = /(<|>|{|})/gi;
var code = document.getElementById("code").textContent;
document.getElementById("output").innerHTML = code.replace(symbols, "<span class='blue'>$1</span>");
The downside is that all your leading whitespaces would be gone.

what is wrong with my html code?

I am new to html. I have been debugging my code for the past 5 hours and I cannot figure out what is wrong with it. I reference a package that only has 1 method, which is get_country. The link to the packages I use are here. https://github.com/nickewing/line-reader and https://github.com/totemstech/country-reverse-geocoding
<html>
<head>
<script type="text/javascript">
function a() {
var lineReader = require('line-reader');
lineReader.eachLine(‘Location.txt', function(line, last) {
var b= line.split(“,”,2)
var lat= parseInt(b[0])
var lng= parseInt(b[1])
var crg = require('country-reverse-geocoding').country_reverse_geocoding();
var country = crg.get_country(lat, lng);
console.log(country.name); //
if (/* done */) {
return false; // stop reading
}
});
}
</script>
</head>
<body>
<button type="button" onclick=“a()>Click run reverse geocoder</button>
</body>
</html>
You're missing a closing quote, you have:
<button type="button" onclick=“a()>Click run reverse geocoder</button>
and it should be:
<button type="button" onclick="a()">Click run reverse geocoder</button>
Aside from the missing quote in the other answer, you have a few quotes that are not standard or double quotes. Here are the ones that a JS parser found:
lineReader.eachLine(‘Location.txt... - The single quote before Location is not a single quote
var b= line.split(“,” - These are not really double quotes - perhaps convert to single quotes or use actual double quotes
Additionally, after your closing brace to the function, you have some extra closing braces and parenthesis.
); - The parenthesis and semicolon
} - The last bracket
Hope this helps
in javascript or in jQuery try to use "" or '' not that curely “” quotes
and its input element in html having attribute type or use button element instead and remove type attribute. hope it would work now
<html>
<head>
<script type="text/javascript">
function a()
{
var lineReader = require('line-reader');
lineReader.eachLine('Location.txt', function(line, last) {
var b= line.split(',',2);
var lat= parseInt(b[0]);
var lng= parseInt(b[1]);
var crg = require('country-reverse-geocoding').country_reverse_geocoding();
var country = crg.get_country(lat, lng);
console.log(country.name); //
if (/* done */) {
return false; // stop reading
}
});
}
</script>
</head>
<body>
<input type="button" onclick='a()'>Click run reverse geocoder</button>
</body>
</html>
EDIT:
sorry IDK why the formating of code it not being applied here.
Syntax error:
onclick="a()" - Missing closing quotes.

Backbone: getting the html code of a view?

In order to write the HTML code of social icons (Twitter, Linkedin, etc) to a textarea so that the user can use that code elsewhere, I would like to get the HTML code of the view element, but I'm having some issues. To help illustrate this better, here is the code that creates the view:
define(function(require, exports, module) {
var _ = require('underscore');
var GridControlView = require('pb/views/grid-control');
var SocialiconsControlDialog = require('pb/views/socialicons-control-dialog');
var template = require('text!pb/templates/socialicons-grid-control.html');
var SocialiconsGridControlView = GridControlView.extend({
template: _.template(template)
,templateVars: {
partials: {
facebook: require('text!pb/templates/socialicons-grid-control-facebook.html')
,twitter: require('text!pb/templates/socialicons-grid-control-twitter.html')
,googleplus: require('text!pb/templates/socialicons-grid-control-googleplus.html')
,pinterest: require('text!pb/templates/socialicons-grid-control-pinterest.html')
,linkedin: require('text!pb/templates/socialicons-grid-control-linkedin.html')
}
}
,control_dialog: SocialiconsControlDialog
});
return SocialiconsGridControlView;
});
And, for example, the Linkedin template looks like this:
<script src="//platform.linkedin.com/in.js?<%- t.cache_buster %>" type="text/javascript">lang: en_US</script>
<script type="IN/Share" data-counter="<%- t.linkedin_option_countmode %>"></script>
What I would like to retrieve, is the parsed template code as text, something such as:
<script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331">
<script data-counter="top" type="IN/Share+init">
But using something such as:
control_view.render().$el.innerHTML;, control_view.render().$el.html().text() or control_view.render().$el.html().replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, ""); doesn't return text; it returns the full HTML, and produces a Linkedin icon (when I just want the text to be written to a textarea).
Any thoughts?
Update **
I noticed that the code control_view.render().$el is working correctly on other places of the application, and returning HTML code, but for some reason in this view where I'm trying it doesn't. The code seems to break at:
$control = control_view.render().el;
and in the console I get an error which is:
TypeError: t is undefined - underscore-min.js (line 3)
Use the .outerHTML property of the $el.
var html = $('<script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331">' +
'<script data-counter="top" type="IN/Share+init">');
var text = html[0].outerHTML;
$('textarea').val(text);
jsFiddle

Categories

Resources