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.
Related
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
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.
I am going through the example given in JavaScript The Complete Reference 3rd Edition.
The O/P can be seen here, given by the author.
<body>
<h1>Standard Whitespace Handling</h1>
<script>
// STRINGS AND (X)HTML
document.write("Welcome to JavaScript strings.\n");
document.write("This example illustrates nested quotes 'like this.'\n");
document.write("Note how newlines (\\n's) and ");
document.write("escape sequences are used.\n");
document.write("You might wonder, \"Will this nested quoting work?\"");
document.write(" It will.\n");
document.write("Here's an example of some formatted data:\n\n");
document.write("\tCode\tValue\n");
document.write("\t\\n\tnewline\n");
document.write("\t\\\\\tbackslash\n");
document.write("\t\\\"\tdouble quote\n\n");
</script>
<h1>Preserved Whitespace</h1>
<pre>
<script> // in Eclipse IDE, at this line invalid location of tag(script)
// STRINGS AND (X)HTML
document.write("Welcome to JavaScript strings.\n");
document.write("This example illustrates nested quotes 'like this.'\n");
document.write("Note how newlines (\\n's) and ");
document.write("escape sequences are used.\n");
document.write("You might wonder, \"Will this nested quoting work?\"");
document.write(" It will.\n");
document.write("Here's an example of some formatted data:\n\n");
document.write("\tCode\tValue\n");
document.write("\t\\n\tnewline\n");
document.write("\t\\\\\tbackslash\n");
document.write("\t\\\"\tdouble quote\n\n");
</script>
</pre>
</body>
(X)HTML automatically “collapses” multiple whitespace characters down to one whitespace. So, for example, including multiple consecutive tabs in your HTML shows up as only one space character. In this example, the pre tag is used to tell the browser that the
text is preformatted and that it should not collapse the white space inside of it. Similarly, we could use the CSS white-space property to modify standard white space handling. Using pre allows the tabs in the example to be displayed correctly in the output.
So, how to get rid of this warning and do i really need to have a concern for this? I think i am missing something as i have the intuition of the authors not being wrong?
There is nothing wrong in having script inside pre tag. It is just Eclipse IDE validation issue. If you use this html in the browser everything works fine and no warnings are displayed.
Also, if you wanted to show script tag as 'text content' inside pre tag, then have a look at this question: script in pre
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/
I need to color the tags in an XML string, which is displayed in the textarea of an html page.
say for example, im having an xml string stored in a variable 'xmldata'.
the textarea tag in html is as below
<textarea id="xmlfile" cols="20" rows="30"></textarea>
using the below javascript statement, im displaying the xml string in the textarea
document.getElementById("xmlfile").value=xmldata;
But the xml string is displayed as a plain text in the textarea.
Is there any javascript function to color the tags in xml ?
I don't want any external javascript and css code work like "google-code-prettify"
All i need is a simple javascript function that colors the tags in an xml string which is displayed in the textarea.
Please help me with a solution.
-Dinesh
Since the contents of your text area are not separate DOM elements I don't believe you'll be able to individually set their attributes (since they don't have individual attributes). You might find some variation on a rich text editor that you can plug in. This may or may not violate your stipulation that you don't want external javascript libraries.
As replied here have a look at a self contained prettifier that works for most cases does nice indenting for long lines and colorizes the output if needed. Nevertheless I guess it might not help if you need it inside a textarea.
function formatXml(xml,colorize,indent) {
function esc(s){return s.replace(/[-\/&<> ]/g,function(c){ // Escape special chars
return c==' '?' ':'&#'+c.charCodeAt(0)+';';});}
var se='<p class="xel">',tb='<div class="xtb">',d=0,i,re='',ib,
sd='<p class="xdt">',tc='<div class="xtc">',ob,at,sz='</p>',
sa='<p class="xat">',tz='</div>',ind=esc(indent||' ');
if (!colorize) se=sd=sa=sz='';
xml.match(/(?<=<).*(?=>)|$/s)[0].split(/>\s*</).forEach(function(nd){
ob=nd.match(/^([!?\/]?)(.*?)([?\/]?)$/s); // Split outer brackets
ib=ob[2].match(/^(.*?)>(.*)<\/(.*)$/s)||['',ob[2],'']; // Split inner brackets
at=ib[1].match(/^--.*--$|=|('|").*?\1|[^\t\n\f \/>"'=]+/g)||['']; // Split attributes
if (ob[1]=='/') d--; // Decrease indent
re+=tb+tc+ind.repeat(d)+tz+tc+esc('<'+ob[1])+se+esc(at[0])+sz;
for (i=1;i<at.length;i+=3) re+=esc(' ')+sa+esc(at[i])+sz+"="+sd+esc(at[i+2])+sz;
re+=ib[2]?esc('>')+sd+esc(ib[2])+sz+esc('</')+se+ib[3]+sz:'';
re+=esc(ob[3]+'>')+tz+tz;
if (ob[1]+ob[3]+ib[2]=='') d++; // Increase indent
});
return re;
}
For demo see https://jsfiddle.net/dkb0La16/