Question

In visual studio and other code editors it is possible to view the white space characters. These would appear as small ellipses in the line.

Is it possible to mimic this feature in html. I have been able to use the pre tag to display the text but I am at a loss on how to display the white space characters.

Is it possible via CSS or javascript to show the white space characters?

Was it helpful?

Solution

You can wrap each space in your pre elements in a span with background, so the spaces become visible, but you could copy the text as usually. Here is a JSFiddle example.

Example script (assuming there are no nested tags in the pre):

var pres = document.querySelectorAll('pre');

for (var i = 0; i < pres.length; i++) {
    pres[i].innerHTML = pres[i].innerHTML.replace(/ /g, '<span> </span>')
}

CSS:

pre > span {
    display: inline-block;
    background: radial-gradient(circle, #cc0, rgba(192,192,0,0) 2px);
}

Alternatively, you can use a custom font for pre elements, in which the whitespace characters are replaced with something visible.

OTHER TIPS

you could replace whitespace chars with the ellipsis symbol, like

jsstring.replace(/[\s]/g, "\u2026");

where jsstring denotes a javascript variable with the text to alter. note that you can get and set the textual representation of an html tag including its contentby means of the jquery html() function.

in case you wish to keep line breaks, use

jsstring.replace(/[ \t]/g, "\u2026");

(example available on jsfiddle: http://jsfiddle.net/collapsar/ARu7b/3/).

in fact, [\s] is just a shorthand for [ \t\r\n]. you may define your own character class containing exactly what you consider to be a whitespace character.

It's impossible to do that by CSS but in Javascript you can do something like this. Note that I used jQuery; if you are not loading jQuery in your project let me know to change my code to plain JavaScript.

for example you have something like:

<pre>
    ul.nav-menu { list-style: none; }
    ul.nav-menu li:last-child { border: none; }
    ul.nav-menu li a { color: #b3b3b3; display: block;  }
</pre>

You can do:

<script>
    var text = $("pre").html();
    $("pre").empty()
    words = text.split(" ");
    for (i = 0; i < words.length; i++) {
        $("pre").append(words[i] + '%');
    }
</script>

And it will replace spaces with any characters like '%' or whatever.
Result will be:

ul.nav-menu%{%list-style:%none;%}
ul.nav-menu%li:last-child%{%border:%none;%}
ul.nav-menu%li%a%{%color:%#b3b3b3;%display:%block;%%}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top