How to replace tabs with four spaces jQuery - javascript

Before you mark this as already asked, just read on!
So I have been searching the web (including StackOverflow) for a way to replace all tabs in an element (more specifically an xmp element) with four spaces. The purpose of this is to show code.
If you visit http://synergytechhosting.com/codeshower.html, you will see my code. The first "totally test code" has one tab before it. The second has four spaces. The four spaces look much more reasonable than the tab. I need it to make all tabs into four spaces so that if someone decides to space with tabs, it will fix it for them rather than making the user do it themselves.
Another problem is that the XMP counts the first line of the code as blank and moves everything down. This can only be solved by doing this:
<xmp><div>
Rather than the normal:
<xmp>
<div>
Basically I need this script to replace tabs with 4 spaces each and remove the first "enter" in the whole thing.
I am already using this to fix the tabs but it doesn't seem to work.
$('xmp').html(function() {
return this.innerHTML.replace(/\t/g, ' ');
});
I just really need this to work and have driven my self insane trying to fix this. I'm pretty sure that this is a really dumb mistake. I expect that because I am a jQuery noob. Is there a better way than using XMP? I'm open to anything and any help at all is super appreciated.
Best Regards,
Emanuel

your script is almost correct, just need to replace with 4 spaces instead of 1
and to remove the first newline, just remove the first character from the string
$('xmp').html(function() {
return this.innerHTML.substring(1).replace(/\t/g, ' ');
});

To trim any leading and trailing whitespace, use jQuery.trim. To re-indent the code from tabs to spaces, without affecting tabs that appear inside the line of code, match the start of the string (^), and use the multi-line flag (m).
$('xmp').html(function(){
return $.trim($(this).html()).replace(/^\t/gm, ' ');
});
Working Example:
$('xmp').html(function(){
return $.trim($(this).html()).replace(/^\t/gm, ' ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<xmp>
<div>
<p>totally test code</p>
<p>totally test code</p>
<p>totally tab code</p>
</div>
</xmp>

The following snippet should work well enough:
$('xmp').html(function () {
return $.trim($(this).html()).replace(/^\t/gm, ' ');
});
It will replace any tab characters at the start of a line with four spaces. Because the regex is anchored with ^, it should not affect anything in the middle of a line.
But here's something you may not have considered: What if the original author of the code had 8-space tabs on the screen, but indented the code with a multiple of 2 or 4 spaces intermixed with those tabs? If the author wanted to indent a block to, say, column 12, they would do something like [Tab] + [4 spaces]. It sounds crazy, but I've seen some projects (Gallery2 comes to mind) that use a combination of tabs and spaces to finely control the indentation. See, the \t character doesn't literally mean "8 (or 4) spaces", it means "jump right until the next column that is a multiple of 8 (or 4)." Because of this, [Tab] + [Tab] generally renders the same on-screen as [Tab] + [2 spaces] + [Tab], yet this regex will convert it very differently.
There is a GNU utility that ships with *nix called expand that is sort of the Swiss Army Knife of converting tabs to spaces. The source is in C, but it's short and there are some interesting insights into just how many edge cases a general-purpose tab-to-space solution could have. http://git.savannah.gnu.org/cgit/coreutils.git/plain/src/expand.c

If you are trying to show spaces in a webpage you will also need to replace the spaces with nbsp First replace tabs with the number of spaces you want, then replace spaces with nbsp
//replace tabs with spaces
msg=msg.replace(/\t/g, ' ');
//replace spaces with
msg=msg.replace(/ /g, '\u00a0');

Related

jQuery/HTML - How do you make a space ( ) take up the same amount of space as another character when using a monospaced font?

I have a simple web page that I'm creating.
In the CSS, I am importing a specific "monospaced" font. Everything is working great, except that the "space" character takes up slightly more space than the other characters.
The problem is that in HTML, you can only use 1 " " string in a row. Otherwise, it obviously ignores the rest. So in case someone types more than 1 in a row, I have to use instead.
But, those spaces seem to take up slighting more space than the other monospaced characters.
What can I do?
Never mind, I figured it out!
Apparently using " " just won't work for me.
What does work is applying "white-space: pre;" to the style of div that the characters are being displayed in.
E.g.
<div style="white-space: pre;"></div>
By doing this, it will now preserve all the consecutive spaces pressed, and I can use the " " string again! :-)
Cool.

Javascript, lines too long in text editor

50 years old, don't have time to spend 6 months learning JavaScript just to do one thing. Comments indicate question too verbose. 1 Found code for blocking JavaScript auto refreshing on a forum. 2 Did web search. 3 Don't know anything about JavaScript. 4 Found conflicting/confusing information. 5 Needed further explanation. The following is the code :
user_pref("capability.policy.policynames", "reload");
user_pref("capability.policy.reload.Location.reload", "noAccess");
user_pref("capability.policy.reload.sites", "http://www.drudgereport.com http://news.yahoo.com");
To add more sites, you simply placed the new site URL into the "" quoted text, making sure to have a space between the URLS. 1. That string could stretch to 100's/1000's of characters. 2. Would look ugly/require scrolling text editor window for days to check for spaces.
Just wanting the code to look good and be able to see everything in the text editor on the code itself (without breaking script execution). Do I just hit enter around the 80 character mark (say after one of the URLS) or do I want to use the \n for a line break?
Thanks for that answer Blender. Not trying to be contentious, didn't know stackoverflow was at a premium for words, edited for brevity. 4 short paragraphs + short code snippet. Hope that is brief enough, can't think of much way to shorten. Out.
You can put them into an array:
var websites = [
'http://www.drudgereport.com',
'http://news.yahoo.com',
...
];
And then join them together to form your string:
user_pref("capability.policy.reload.sites", websites.join(' '));
Or all at once:
user_pref("capability.policy.reload.sites", [
'http://www.drudgereport.com',
'http://news.yahoo.com',
...
].join(' '));
user_pref("capability.policy.policynames", "reload");
user_pref("capability.policy.reload.Location.reload", "noAccess");
user_pref("capability.policy.reload.sites", "http://www.drudgereport.com http://news.yahoo.com");
why not just use word wrap if using Notepad++?
Select “View” from menu bar.
From the dropdown menu that appears click on “Word wrap” option.
The same procedure is used to swap between Word wrap On & Off.

Highlight Non-breaking spaces in HTML page or WordPress editor

While editing in WordPress, I sometimes use non-breaking spaces in headers so that words stay together. When I save, the non-breaking spaces are there, but they look like normal spaces, so I can't see them.
Also, WordPress creates non-breaking spaces when I type in the body of my post, which I have to remove somehow.
I thought it'd be easy to create a bookmarklet that uses jQuery to highlight non-breaking spaces in a web page or the editor. However, I'm no good with regular expressions, or maybe there's something else I'm doing wrong. Here's the jQuery code:
$('p').html($('p').html().replace(/ [\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/g, '<span class="red"> </span>'));
Here's a jFiddle:
https://jsfiddle.net/y18e0c1w/
========
Maraca helped me out here (see below). I created the bookmarklet with his code, and added a white-space:nowrap to the span so that you can still see the highlight if it’s at the end of a line. Here it is:
javascript:function%20escapeRegExp(e){return%20e.replace(/([.*+?^=!:${}()\]\[\/\\])/g,"\\$1")}function%20replaceAll(e){return%20e.string.replace(new%20RegExp(escapeRegExp(e.search),"g"),e.replace)}jQuery("body").html(replaceAll({string:jQuery("body").html(),search:" ",replace:'<u%20style="background:#FF0;white-space:nowrap">%20</u>'}));
Remember, it relies on jQuery already being loaded on the page. It doesn't play nice with the WordPress backend, but it works on the frontend and that's good for me right now. Hope someone else finds this useful too.
Got it: https://jsfiddle.net/y18e0c1w/2/
function escapeRegExp(s) {
return s.replace(/([.*+?^=!:${}()\]\[\/\\])/g, '\\$1');
}
function replaceAll(p) {
return p['string'].replace(new RegExp(escapeRegExp(p['search']), 'g'), p['replace']);
}
$('p').html(
replaceAll({
string: $('p').html(),
search: ' ',
replace: '<span class="red"> </span>'
})
);
The first two functions are just helper functions. Then I replace by a span, that's it.
Note that I used a normal space in the span, because then there is no problem with repeated execution. Otherwise you would wrap the with span tags each exection.
The quick and dirty solution for the whole body: https://jsfiddle.net/y18e0c1w/7/

How do I allow <img> and <a> tags for innerHTML, but no others? (Making a forum)

I am currently programming a forum using only javascript (No JQuery please). I am doing very well, however, there is one issue I would love help with.
Currently I am getting the post from a database, assigning it to variable MainPost, and then attaching it to a div via a text node:
var theDiv = document.getElementById("MainBody");
var content = document.createTextNode(MainPost);
theDiv.appendChild(content);
This is working quite well, however, I would LOVE to be able to do this:
document.getElementById("MainBody").innerHTML += MainPost;
But I know this would allow people to use ANY html tag they want, even something like "script" followed by javascript code. This would be bad for business, obviously, but I do like the idea of allowing posters to use the "img" tag as well as the "a href" tags. Is there a way to somehow disable all tags except these two for the innerHTML?
Thank you all so much for any help you can offer.
Ok, the first thought that came to my mind when I read this question was to find a regular expression to exclude a specific string in a word. Simple search gave a lot of results from SO.
Starting point - To remove all the HTML tags from a string (from this answer):
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
To exclude a string you would do something like this (again from all the source mentioned above):
(?!StringToBeExcluded)
Since you want to exlcude the <a href and <img tags. The suitable regex in your case could be:
(<(?![\/]?a)(?![\/]?img)([^>]+)>)
Explanation :
Think of it as three capturing groups in succession:
(?![\/]?a) : Negative Lookahead to assert that it is impossible to match the regex containing the string "a" prefixed by zero or one backslashes (Should take care of the a href tags)
(?![\/]?img) : Same as 1, just here it looks for the string "img". I don't know why I allowed the </img> tag. Yes, <img> doesn't have a closing tag. You could remove the [\/]? bit from it to fix this.
([^>]+) : Makes sure to not match > zero or one times to take care of tags that have opening and closing tags.
Now all these capture groups lie between < and >. You might want to try a regex demo that I've created incorporating these three capture groups to take care of ignoring all HTML elements except the image and link tags.
Sidenote - I haven't thoroughly given this regex a try. Feel free to play around with it and tweak it according to your needs. In any case, I hope this gets you started in the right direction.

Preserving Newlines When Using ".text" or ".textContent". Possible? Alternatives? Workarounds?

If I grab some html from one element, then attempt to assign it as the text content of another element, newlines are not preserved (at least not in the latest Firefox and Chromium).
So, for example, the follow code (with sensible html) produces output where the newlines are replaced by spaces. Well, except the alert, which works as expected.
$("#info").data("html", $("#info").html());
$("#jquery").text($("#info").data("html"));
document.getElementById("javascript").textContent = $("#info").data("html");
$("#alert").click(function() { alert($("#info").data("html")) });
Here's a running example: http://jsfiddle.net/76S7z/2/
There should be some method of setting the html of one element as the text of another while preserving newlines properly.
Is this possible with "text" or "textContent"? Is there an alternative way to do this? Is there a simple workaround? A less than simple workaround?
As you've already determined, Web browsers don't normally render newline characters \n as line breaks. If you're resistent to adding the line break element <br />, you can use the white-space CSS property with the value pre-line, which will:
Sequences of whitespace are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.
Be sure to check the property's compatibility tables before using.
<div style="white-space: pre-line;">
Look
at
these line breaks!
</div>
Here's a JSFiddle example.

Categories