jQuery custom markdown for a blockquote - javascript

I want to create my own markdown system for my platform.
So, to allow users to make their text bold, they can wrap text in double asterisks.
Here is how I do this:
<div class="content">
The following will be bold: **I am bold**
</div>
jQuery:
function markdown(markdownable) {
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
markdownable = markdownable.replace( bold, '<span style="font-weight:bold">$1</span>' );
return markdownable;
}
$('.content').each(function() {
var markdownable = $(this).html(),
content = markdown(markdownable);
$(this).html(content);
});
Here is a working fiddle.
Now, to my question. Whenever users add a > at the beginning of a paragraph, like this:
> Hello world, this can be a very lengthy paragraph.
Then I want to wrap that text into <blockquote>.
How can I do this?

hey i have updated your jsfiddle..
code:-
function markdown(markdownable) {
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
markdownable = markdownable.replace(bold, '<span style="font-weight:bold">$1</span>');
if (markdownable.indexOf(">") == 0) {
markdownable = markdownable.replace(">", "<blockquote>");
markdownable += "</blockquote>";
}
return markdownable;
}
$('.content').each(function() {
var markdownable = $(this).html(),
content = markdown(markdownable);
$(this).html(content);
});
working jsfiddle example:-
http://jsfiddle.net/dwxmjkb3/2/
new Code as per request:-
function markdown(markdownableOrg) {
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
var dataArray = markdownableOrg.split("\n");
var data = [];
for (var i = 0; i < dataArray.length; i++) {
var markdownable = dataArray[i];
markdownable = markdownable.replace(bold, '<span style="font-weight:bold">$1</span>');
if (markdownable.indexOf(">") == 0) {
markdownable = markdownable.replace(">", "<blockquote>");
markdownable += "</blockquote>";
}
data.push(markdownable)
}
return data.join("\n");
}
now above given method splits the data(each line) and checks for > and replace it with blockquote.
updated jsfiddle :-http://jsfiddle.net/dwxmjkb3/6/
thanks

Related

Javascript: Can't pull the .text() from an html tag

I'm editing this to add my solution based on georg's answer. The solution is at the bottom.
I am trying to get the enclosed text from a given tag using.
var substring = txt.find(tag).eq(i).text();
Sample Data:
The variable tag holds "h1".
The variable txt holds "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>".
The Expectation:
subString == "fish"
The Result:
subString == null
Code:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_tagToText(tag);
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return result;
} catch(e) {
console.log(e);
return false;
}
}
Solution:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_tagToText(tag);
var substring = jQuery('<div>').html(txt).find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return result;
} catch(e) {
console.log(e);
return false;
}
}
To use find you have to put your html in a container:
txt = "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>";
result = $('<div>').html(txt).find('h1').text()
alert(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is how I would do it:
var tag="h1"
var txt = "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>";
var result = txt.match(new RegExp("<"+tag+">(.*)</"+tag+">"));
console.log(result[1]);
alert(result[1]);
Here is the JSFiddle demo
The string was filtered using the tag u provided via regex and the text between the tags are shown as a message.
I have tried doing in a similar fashion and was able to do it quite well.
Please refer demo.
Code below:
HTML:
<div class="test">Test div 1</div>
<div class="test">Test div 2</div>
<div class="test">Test div 3</div>
<div class="newDiv"><p>New Div</p></div>
JS:
$(function(){
var len = document.getElementsByClassName('test').length;
for(var i = 0; i<len;i++){
var test = $('.test').eq(i).text();
$('.newDiv').append('<br>Loop ' + (i+1) + ' text = ' + test);
}
});

Replace a space within a SPAN tag with a BR tag

I need to replace the space between the 2 words with a BR tag. I've tried quite a few things, this one I thought would work, but the original script only does it to the first item. :( I need it to replace it on all the menu items.
It's for menu text on a CMS, so I won't know what the text is going to be. All I know is that it will always be no more than 2 words.
I can use either JS or jQuery.
Demo here: JS Bin Link
HTML:
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
JavaScript:
// Doesnt work
// var span = document.getElementsByTagName(".navtext");
// Only works for the first one
var span = document.querySelector(".navtext");
// Doesnt work
// var span = document.querySelectorAll("navtext");
function space() {
var elem = document.createElement("br");
// elem.className = "space";
// elem.textContent = " ";
return elem;
}
function replace(elem) {
for(var i = 0; i < elem.childNodes.length; i++) {
var node = elem.childNodes[i];
if(node.nodeType === 1) {
replace(node);
} else {
var current = node;
var pos;
while(~(pos = current.nodeValue.indexOf(" "))) {
var next = current.splitText(pos + 1);
current.nodeValue = current.nodeValue.slice(0, -1);
current.parentNode.insertBefore(space(), next);
current = next;
i += 2;
}
}
}
}
replace(span);
I think, you dont want to use jQuery. Well, Here is quick solution:
var elms = document.querySelectorAll(".navtext");
for(var i=0; i<elms.length; i++){
elms[i].innerHTML = elms[i].innerHTML.replace(/\s/gi, "<br />");
}
Here is the jsfiddle: http://jsfiddle.net/ashishanexpert/NrTtg/
using jQuery you can do this:
$("span.navtext").each(function(){
$(this).html($(this).text().replace(/ /g,"<br />"));
})
If you install jQuery you can make it all more simple. Follow the installation instructions and then the code you'll need is something like:
jQuery(function($) {
// for each navtext run the described function
$(".navtext").each(function() {
// "this" represents the navtext
// replace all " " with "<br/>" from this's html
var code = $(this).text();
code = code.replace(" ", "<br/>");
// update this's html with the replacement
$(this).html(code);
});
});
Someone on twitter provided me with a fix, which was exactly like what Ashish answered.
var spans = document.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}
But that would quite work for me, but it did give me my answer! So thanks to Pete Williams
This is the code I went with:
var spans = document.querySelectorAll('.navtext');
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}

Adding a span to a particular word in a contendEditable div?

I have a div which is content editable, and JS function to search the input for certain words. If a match is found, the content od the div turns blue, but I want only the matched word to turn blue. How can I do this?
Here is my JS...
function init() {
window.setInterval(function() {
var div = document.getElementById("texty");
var html = div.innerHTML;
var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];
for(var i = 0; i < buzzword.length; i++)
{
var regex = new RegExp(buzzword[i], 'g');
html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
}
div.innerHTML = html;
}, 100);
}
and my HTML is this...
<div id="texty" contenteditable="true" onfocus="init()"></div>
Get the html of the div then do a regex replace and add a span around the word. Code would look something like this:
var escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
var div = document.getElementById("texty");
var html = div.innerHTML;
var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];
for(var i = 0; i < buzzword.length; i++)
{
var regex = new RegExp(escape(buzzword[i]), 'g');
html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
}
div.innerHTML = html;

Get overlib text with jquery

I'm writing my own grease monkey userscript.
I want to edit the overlib text using jquery.
This is what it looks like in HTML code:
<div class="expbar" onmouseover="return overlib('Some text',HAUTO,WIDTH,250,CAPTIONFONTCLASS,'action-caption',TEXTFONTCLASS,'overlibText overlibExtended',VAUTO,CAPTION,'POZIOM 44');">
I like to get the overlib popup text in a variable in jquery, "Some text".
I would also to be able to change that text.
Can not figure out how to do this.
This is what I can do:
var oldText = $(".expbar[onmouseover]").attr("onmouseover");
but then oldText contains whole "return overlib('Some text',HAUTO,WIDTH,250,CAPTIONFONTCLASS,'action-caption',TEXTFONTCLASS,'overlibText overlibExtended',VAUTO,CAPTION,'POZIOM 44');"
Please some help.
Got it working.
GM_log("Level bar upgrade");
var oldAll = $(".expbar[onmouseover]").attr("onmouseover").split("'");
var oldText = oldAll[1];
oldText += "\\r\\r<br />Injection test";
var newAll = "";
for (var i = 0; i < oldAll.length; i++) {
if(i == 1)
{
newAll += oldText;
}
else
{
newAll+=oldAll[i]
}
if(i != oldAll.length - 1)
{
newAll += "'";
}
}
$(".expbar[onmouseover]").attr("onmouseover", newAll);

Continuously loop through JavaScript text array onclick

I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
Here's what I have
$(document).ready(function(){
var arr = new Array("One","Two","Three");
var len=arr.length;
$('#next').click(function(){
for(var i=0; i<len; i++) {
$('#quote').html(arr[i]);
}
});
});
Something like the following should do the trick:
<script type="text/javascript">
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var count = -1;
return function() {
return wordArray[++count % wordArray.length];
}
}());
</script>
<p id="foo"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
Radomised version:
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var copy;
return function() {
if (!copy || !copy.length) copy = wordArray.slice();
return copy.splice(Math.random() * copy.length | 0, 1);
}
}());
The following should do it http://jsfiddle.net/mendesjuan/9jERn/1
$(document).ready(function(){
var arr = ["One","Two","Three"];
var index = 0;
$('#next').click(function(){
$('#quote').html(arr[index]);
index = (index + 1) % arr.length ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
I think something like this would work
The javascript would look like:
// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
textDisplayIndex += 1;
if (textDisplayIndex > maxTextArrayIndex)
{
textDisplayIndex = 0;
}
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}
The html would look like:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>

Categories

Resources