Automatically recognize an image from textarea (like StackOverflow) - javascript

I would like to create my own "editor" (only code-view, no WYSIWYG) and I have a problem with inserting images. Uploading and selecting images is done via blueimp-jQuery-File-Upload.
What I would like to do is insert them into my textarea in the same way that StackOverflow does it (so without some fancy galleries, modules etc). I upload it and it automatically add's in a textarea in this format
![imageDescription][1]
[1]: http://i.stack.imgur.com/image.jpg
My question is how to do (probably with jQuery/JavaScript) automatic recognition if some image is present in my text area (so if I have these two lines in my textarea), below textarea those images are displayed (or their links) but if I delete them (text lines) - those links/images below disappear.
Probably I should do some "scanning" line by line on every keypress? Maybe with regular expression so if it's true (for both lines) - then display the image below, instead it's just a regular text.

If you want to show those images instantly below your editor, you have no choice but binding that thing to an keypress event. When you get the text you could do some regex action to catch the image and insert it into an <img src="my image">. After that check after every press if the imageurl is still present in that editor (maybe a history is a good choice). If not, delete the <img> tag.

If it's still needed, here's some reference that I made.
Javascript regex replacements:
.replace(new RegExp("\_img_([^ ].+?[^ ])\_img_", "g"),"<img src='$1' />")
Its actually a pattern that could be applied to just about any tag. The regex is as follows:
.replace(new RegExp("\___what ever signifier here ___([^ ].+?[^ ])\_____end sign____", "g"),"<tag>$1</tag>")
*remember to escape special characters in the regex like * with twp forward slashs like so: \\*
also, if you want to add more parameters, just add another ([^ ].+?[^ ]) block and then name where the next parameter will go with $2 like so:
.replace(new RegExp("\\[([^ ].+?[^ ])\\]\\(([^ ].+?[^ ])\\)", "g"),"<a href='$1'>$2</a>")
notice that I escaped [ ] ( ) with double forward slashes.
See it in action: http://jsfiddle.net/xwTGr/

Related

Wrapping text to the next line after a fullstop or condition?

Is it possible to move text to the next line after a full stop?
For example with a standard h1 header - 'This is a very. Very. Big header.'
But I want my headers to move to the next line after a fullstop -
'This is a very.
Very.
Big header.'
My goal is to have every title h1 fetched from an API to for formatted so the line wraps every time there is a fullstop '.'
Code:
<div className='quote-wrapper'>
<h1 className='quote'>{currentQuote.quote}</h1>
</div>
I don't believe there is a way this can be achieved as a CSS style or HTML property. Look into word-wrap and text-overflow incase they work for you, though.
In JavaScript, this is easy. Just find all the elements you want to change (like all h1's, get their current text with .innerText or .innerHtml, and then set their current text to be their old text but replace all the periods with newlines.
document.querySelectorAll("h1").forEach((x) => {
x.innerText = x.innerText.replace(/\./g, "\n")
})
Here, document.querySelectorAll("h1") gets a list of all h1's on the page. You could make it something like ".quote" to select by class, etc.
forEach(...) takes a function (the (x) => {...} thing) and applies it to each item in the list.
In our function x.innerText is the text inside the h1 element and replace replaces everything matching the first argument (/\./g) with the second argument ("\n"). Here, /\./g is the regular expression for "all periods" and "\n" is the newline character.
Edit:
It looks like you are using React so you don't actually need to do anything with a querySelector. Just perform the replace on currentQuote.quote right before you put it into the DOM
You can do it by using the split method.
Here is how i did it.
https://code.sololearn.com/W85wKQly9I7a/?ref=app

Parsing plain text Markdown from a ContentEditable div

I know there are other questions on editable divs, but I couldn't find one specific to the Markdown-related issue I have.
User will be typing inside a ContentEditable div. And he may choose to do any number of Markdown-related things like code blocks, headers, and whatever.
I am having issues extracting the source properly and storing it into my database to be displayed again later by a standard Markdown parser. I have tried two ways:
$('.content').text()
In this method, the problem is that all the line breaks are stripped out and of course that is not okay.
$('.content').html()
In this method, I can get the line breaks working fine by using regex to replace <br\> with \n before inserting into database. But the browser also wraps things like ## Heading Here with divs, like this: <div>## Heading Here</div>. This is problematic for me because when I go to display this afterwards, I don't get the proper Markdown formatting.
What's the best (most simple and reliable) way to solve this problem as of 2015?
EDIT: Found a potential solution here: http://www.davidtong.me/innerhtml-innertext-textcontent-html-and-text/
if you check the documentation of jquery's .text() method,
The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)
so getting whitespaces is not guaranteed in all browsers.
try using the innerText property of the element.
document.getElementsByClassName('content')[0].innerText
this returns the text with all white spacing intact. But this is not cross browser compatible. It works in IE and Chrome, but not in Firefox.
the innerText equivalent for Firefox is textContent (link), but that strips out the whitespaces.
This is what I've been able to come up with using that link I posted above in my edit. It's in Coffeescript.
div = $('.content')[0]
if div.innerText
text = div.innerText
else
escapedText = div.innerHTML
.replace(/(?:\r\<br\>|\r|\<br\>)/g, '\n')
.replace(/(\<([^\>]+)\>)/gi, "")
text = _.unescape(escapedText)
Basically, I'm checking whether or not innerText works, and if it doesn't then we do this other thing where we:
Take the HTML, which has escaped text.
Replace all the <br> tags with line breaks.
Strip out any tags (escaped ones won't be stripped, i.e. the stuff the user types).
Unescape the escaped text.

how to display whitespace characters.. but omit when text is selected

Setup:
I'd like to output some text that shows visible spaces, linebreaks, etc
(For the purpose of displaying strings for debug purposes (or for say a rich-text editor))
ie, id like to make the following type of substitutions
" " -> "<span class="whitespace">·</span>"
"\r" -> "<span class="whitespace">\\r</span>"
"\n" -> "<span class="whitespace">\\n</span>"
perhaps the following CSS rule could be defined
/*display whitespace chars as a light grey*/
.whitespace { color:#CCC; }
so that
this two line
string
would be displayed as
this·two·lined\n
\t string
The Question:
Is it possible so that when the above "visual-whitepace" text is selected / copied-to-clipboard... it copies without the whitespace markup?
Is there some CSS property to display x, but copy y?
javascript hack?
special whitespace-font?
other?
<style>.paragraph-marker:after { content: "\B6" }</style>
<p>Foo<span class="paragraph-marker"></span></p>
<p>Bar<span class="paragraph-marker"></span></p>
The :after is a "pseudo-selector" which matches a pseudo-node that immediately follows the affected element.
The content property can be used with these pseudo-nodes to specify the textual content of them. It comes in handy when specifying quotation marks before and after quoted sections, or list separators like commas in semantic HTML <ol> which you don't want to display in bullet format.
It should come in handy for your use case since browsers don't deal with pseudo-nodes when converting a DOM selection stored in the clipboard to plain text on paste.
http://codepen.io/msvbg/pen/ebgrj
Works fine in the latest version of Chrome. Flip the showWhitespace variable to try it both ways. It works by sticking a visible whitespace layer underneath the text layer, and only the top-most layer is copied by default.

Use JS to replace text in Gmail message body

I want to write an GnuPG extension for Google Chrome. So far, everything works as expected: If I detect ASCII armored crypt-text, I parse it with my extension and then replace it. (after password has been entered)
Gmail however litters the message body with an insane amount of tags, so my simple JS approach doesn't work anymore. Is there something which can select an certain amount of visible text, no matter how many tags are contained in it, and replace it with some other text? (the tags don't need to survive). ie I want to unencrypt the mailbody in place.
what do you need is something like this:
/<[^>]+>/g
this regexp will remove all tags, an leave plain text...
just gotta replace for nothing... something like this:
"<p>text <b>full</b> of <i>junk</i> and <u>unwanted</u> tags</p>".replace(/<[^>]+>/g, "");
...and about selecting an specific part you can use substring, I guess!
What I really needed to do was a little different:
expand my regex so it didn't care about tags:
var re = /-----[\s\S]+?-----[\s\S]+?-----[\s\S]+?-----/gm;
store all the matches, with tags
use the regex provided by gibatronic to remove tags and then further process the cleaned text using gpg
use body.innerHTML.replace() to replace the matches from 1) with the processed text from 3)
It works now, the only problem is it breaks Gmail. Site layout stays intact, but all buttons and links become defunct. Only solution is to reload the page. Gotta fix this :S

how to show arabic alert from left to right

How to show java script alert of arabic characters/text from ltr(Left to right) format.In html we have ltr tag.
This is largely operating system dependent. Simply reversing the string is not 100% correct, since this does not render punctuation correctly.
If you need 100% locale independence in the browser, I would suggest using an HTML dialog, like jQuery UI, instead of alert().
You can't do it using the regular javascript alert()
however, you can use some custom javascript alert box (you can use HTML inside it)
some like this http://slayeroffice.com/code/custom_alert/ or http://jdstiles.com/java/jsalert.html
Hi, this is possible using unicode control characters:
- variable 'g' without ucc
var g="أكتب تعليقا!\nWrite a comment!\n";
variable 'g' with ucc
var g="‫أكتب تعليقا!\n‪Write a comment!\n";
or
var g="‫أكتب تعليقا!\n‪Write a comment!\n";
simply:
place (LRE) character (‪‪‪) in multi-dir texts where embedded texts start from left-to-right;
place (RLE) character (‫) in multi-dir texts where embedded texts start from right-to-left.
or on your win notepad right click where embedded text start, insert unicode..., (LRE) or (RLE)

Categories

Resources