简体   繁体   中英

Automatically recognize an image from textarea (like StackOverflow)

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM