Javascript, lines too long in text editor - javascript

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.

Related

Isolate first and last letter in JS Word Search code

I am trying to build a WordSearch game; I'd like to use this Github repo:
https://github.com/bunkat/wordfind
I am not very good with JavaScript and I was wondering if anyone with more chops than me could take a look at this well formatted code on GitHub and say whether they can see how I can modify it.
I would like to add a class or attribute to the first and last letter of a word, in order that I can style it with CSS to have rounded corners?
Doesn't matter if it's when generating the grid, or when selecting a correct answer.
I hope you have some advice. Many thanks in advance.
Just a point in the right direction would be a big help.
Check the example here : http://bunkat.github.io/wordfind/example/index.html
After finding a word - the class of each letter from the found word goes from puzzleSquare to puzzleSquare found
You could add a javascript function that will find all the puzzleSquare found that are next to each other. Then you add a class to the first and last element of this array

How to replace tabs with four spaces jQuery

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');

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.

How to highlight dates in a paragraph?

I'm trying to figure out how to select dates (note: all dates, not just specific dates) in a paragraph using (I'm assuming) jQuery/Javascript.
To give an example, the website gets a bunch of text from a database, and in that text is included a date in the following format: (DD/MM/YYYY). I just want to highlight everytime that comes up, but I'm not sure how because sometimes the date can be 02/09/2014 or 13/10/2014, so I can't just search for a certain date and highlight it.
Any help is appreciated :) Thanks!
I think what you may be looking for is something like this. Here is a jsFiddle Example
$("div").html($("div").html().replace(/(\d{1,2}\/\d{1,2}\/\d{4})/gi, "<span style='background-color:yellow;'>$1</span>"));
Here is the same code above only on different lines for easier reading.
$("div")
.html(
$("div")
.html()
.replace(/(\d{1,2}\/\d{1,2}\/\d{4})/gi,
"<span style='background-color:yellow;'>$1</span>"
)
);
First we group the regEx with a left and right parentheses. This is now able to be referenced as parameter $1. We then look for the pattern we are seeking (do not forgot to add the gi at the end so that you look for all occurrences, not just the first one.
We then replace our find with a span tag so that we can style the contents, in this case a yellow background and we still want the date we found so we add in the $1 to put the date inside the span tags.
Hope this helps
Here's a super basic regex that will find 'datelike' number series:
\d{1,2}/\d{1,2}/\d{4}
Try it out here: http://regexhero.net/tester/
Using some text like "This is some text for the regex hero on 9/2/2014. I think for the most part it will work for what you are looking for on 9/3/2014."
In fact, here's some javascript to play with (using jquery):
http://jsfiddle.net/5z7bz4zm/2/
<div>
This is some text for the regex hero on 9/2/2014. I think for the most part it will work for what you are looking for on 9/3/2014.
</div>
$(document).ready(function() {
$("div").text($("div").text().replace(/\d{1,2}\/\d{1,2}\/\d{4}/, "<span>caught ya</span>"));
});

Multiple character replacements in JS - how to stop replacements on previous results within the same function

I have a ( probably very unclean) script that I intend to convert letters put into a text field into html image tags with corresponding pathways. I know there are probably easier ways of doing this, PHP for example however I am using it as a bit of an experiment to familiarise myself further with JS/Jquery. I have overcome a few obsticles to get where I am now as most of this is new ground for me.
In some cases the letters will have multiple images associated with them that will be selected at random so there are a couple of lines included which do this. These are fine however, the issue comes with the section of code that replaces the letters from the text field with the text and variables that make up the image tag. Whilst they work fine individually, when I want to convert multiple letters the replace overwrites instances of that letter in the previously generated image tag. Any ideas can I stop this? I've tried shifting the points at which the script occurs around but it seems the whole thing is somewhat fragile and haven't been able to create a workable solution.
Code in question:
// replace all instances within variable to generate thumbs
final_result = result.replace(/a/g, str_start+chosen_folder+"a"+random_variation+str_end)
.replace(/e/g, str_start+chosen_folder+"e"+random_variation+str_end);
JS Fiddle here: http://jsfiddle.net/N77wZ/
Many thanks in advance !
Do only a single replace:
final_result = result.replace(/a|e/g, str_start+chosen_folder+"$&"+random_variation+str_end);

Categories