I'm working on a bookmarklet which is using the replaceText plugin to wrap all words (and extraneous spaces/punctuation) on a page in span tags. That plugin traverses all the text nodes on a page and allows me to call a function to manipulate the contents of each one without breaking any other HTML formatting on the page. (None of this is the problem, I'm pretty sure, but I felt like the context might be useful). My call of the function looks like this, for your reference:
$("body *").replaceText(/\S+\s*/g, spanWrap);
The problem is that the best regular expression I've found for separating these words for my purposes -- /\S+\s*/g -- contains the characters for the end of a block comment ("*/"). If I add the opening of a block comment a few lines before it in the .js file in Notepad++, I can see that the syntax highlighter is reading it as that.
When I run my bookmarklet, most sites seem to have no problem with this issue and the bookmarklet works as intended. However, some sites, for reasons I can't predict, throw up an "Uncaught SyntaxError: Unexpected token <" error and the bookmarklet breaks/stops running. If I change the regular expression I'm using in the replaceText function to one I had been using in an earlier version of the bookmarklet -- /\b(\S+?)\b/g -- while changing absolutely nothing else in the bookmarklet, these sites stop giving the error and the bookmarklet works just fine, so I have to believe that it's the presence of the block comment closure that's causing it.
For the purposes of what I'm trying to do with the bookmarklet, though, the expression with that comment closure in it --/\S+\s*/g-- works much, much better than the other one, which doesn't catch punctuation and white space. However, I'd also really like it if my bookmarklet didn't break on certain sites.
So, is there either a way to fix the regular expression that I have so that it's not being read as a comment or can you suggest one that can do the same job maybe with a different syntax or something? (If it's not obvious from my question, I have the barest understanding of how regular expressions work and have gotten the ones I'm using in this example by copying them from other Stack Overflow questions/answers)
Use the long version:
var regex = new RegExp("\\S+\\s*", "g");
$("body *").replaceText(regex, spanWrap);
(EDIT: Escaped the backslashes in the string)
So, is there either a way to fix the regular expression that I have so that it's not being read as a comment
I can't think of anything sane. (You could get the effect by using the RegExp constructor and breaking the regex up into two strings and then concatenating them back together for the regex. I wouldn't call that sane though.)
I'd use a series of line comments // instead of a block comment.
Related
I am creating a chrome javascript bookmarklet with reference to:
this question
My code:
javascript:(function NoOverrideAction(t){this.currentWindow=t,this.urlMatchPattern=/https:\/\/.*visual\.force\.com\/apex\/.*/,this.urlMatchPattern1=/https:\/\/.*visualforce\.com\/apex\/.*/,null!=this.currentWindow.location.toString().match(this.urlMatchPattern)||null!=this.currentWindow.location.toString().match(this.urlMatchPattern1)?this.isPageValid=!0:this.isPageValid=!1,this.recordId} NoOverrideAction.prototype={getId:function(){this.currentWindow.location.search.substr(1).split("&").forEach(function(t){var i=t.split("=");"id"==i[0]&&(this.recordId=i[1])},this)},run:function(){this.getId(),console.log(this),this.isPageValid&&void 0!==this.recordId&&(this.currentWindow.location.href="https://"+this.currentWindow.location.hostname+"/"+this.recordId+"?nooverride=1")}};var noAction=new NoOverrideAction(window);noAction.run();)();
However, I get following error:
Uncaught SyntaxError: Unexpected identifier
This works well in console but not as a bookmarklet.
I am trying to verify the URL of my current page and replace the URL
Part I.
Several reasons why js-code might work in console, but not work as a bookmarklet.
1 - You don't use the established way of making bookmarklets, i.e. IIFE-functions.
javascript:(function(){
alert('hi');
/*code here*/
})();
2 - If you do use this structure, there might be the problem with comments.
Use /*multi-line comment*/ instead of //single-line comment (because bookmarklet is a one-liner, so you cannot close your comment)
3 - Some problems with semicolons ;.
Don't confuse statements (need semicolon) and assignments (do not need them).
Console has its "automatic semicolon insertion", but it is a problem for a one-lined bookmarklet.
You should read a bit more here: https://stackoverflow.com/a/2717956/5410914
Part II
Since there is no HTML-code to test, it might be hard to check. Moreover, you could have made it easier to read by making it multi-lined (it will still work as a bookmarklet when you paste it as a bookmark). But anyway.
The main reason it might not work is that you don't use IIFE-format (Immediately Invoked Function Expression).
Your code has function NoOverrideAction(t) and, moreover, there is };var noAction=new NoOverrideAction(window);noAction.run();)(); at the end. It is not IIFE.
Read more: https://developer.mozilla.org/ru/docs/Glossary/IIFE
To debug a bookmarklet on your own, since there is no HTML provided, you might try to make your code simplier (even with alert('hi'); at first, and verify the reason it won't start) and then make it more complicated once you figure out that it works.
I have a large javascript file that is missing a lot of semicolons. It works fine as it is, but when I try to use a minifier = kaboom! Is there a way to automatically fix this? I tried to go manually through it but it's not humanly possible.
check out the JavaScript Lint application that checks your script for common errors (semicolon, curly brackets, trailing decimals, nested comments, etc.)
I'm quite puzzled by this one, getting this error from firefox.
escape is not a function
Looking at the W3C page, it says it is supported as I thought.
I tried escapeURI instead and this produced the same error.
Any suggestions ?
There is an escape function in DOM level 1 so your code should work. The most likely explanation for the problem is that you have either overwritten it or declared a new escape variable in a local scope. If the latter, then you should be able to get access to it via window.escape.
You shouldn't be using this function anyway; it has been deprecated because it doesn't handle non-ASCII characters very well. Use encodeURIComponent instead.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Lambda function syntax in JavaScript without curly braces
Dealing with Protovis - they implement some strange delegate functions which are given without curly braces - can someone shade a light on it for me, please?
Example:
vis.add(pv.Label)
.data(cols)
.left(function() this.index * w + w / 2)
.top(0)
.textAngle(-Math.PI / 2)
.textBaseline("middle");
In general, as explained in the question #missingno linked to, this is an alternate syntax for declaring functions, primarily supported by Firefox. Instead of:
function() { return "stuff" };
you omit the curly braces and return statement:
function() "stuff";
The end of the function occurs anywhere that a normal statement might end - a semicolon (;), a comma (,), or a close parenthesis ()).
In Protovis, there are a lot of cases where you need to declare short, one-statement anonymous functions to pass in as arguments to method calls. This is such a common pattern that that library includes a parsing utility to make sure that the above syntax is supported in browsers other than Firefox. If you enclose your Protovis code in script tags like this:
<script type="text/javascript+protovis">
// ...
</script>
the script will be evaluated by the Protovis parser, which ensures support for the special syntax.
My two cents on this: The upside of this syntax is that it's really fast (plus all the examples use it). A typically script using Protovis involves a lot of anonymous functions, so this can save you some typing, and it looks pretty awesome. When I first started using Protovis, I used it a lot - not just in method calls, but in variable declarations as well.
But, it has a few really heavy problems:
Because all your code is run through the Protovis parser, which essentially munges the code to re-add the return statements and then eval() it, it becomes fantastically hard to debug simple syntax errors. You get all these "Unexpected identifier" errors pointing to the eval() line in the Protovis code, with no indication of where the issue (a missing semicolon, etc) is occurring in your own code.
If you want your code to work outside Firefox, you have to include all your code in the special javascript+protovis script tags, which means no external files. Once you start doing anything of even marginal complexity, you really want to keep your scripts separate most of the time.
As with any "clever" syntax, it can get really hard to read, especially when you're using it in unexpected ways (e.g. outside of a method call). Yes, it's concise, but there's a definite price to pay in legibility.
All that said, I still use it when I want to make a rough sketch quickly. But most of the time, I'd suggest sticking to normal script tags and standard, curly-braced function declarations.
I'm using NSXMLParser on an iPhone App to parse HTML Files for a RSS or Atom Feed Link.
Everything works fine until the parser find a <script> element that includes Javascript code without the CDATA Declaration, this causes a Parse Error.
Is possible to tell the parser to skip all the elements named <script>?
Why not just implement parser:parseErrorOccured: and tell it to fail gracefully? I don't believe there's a way to say 'skip this element'
It's not possible to my knowledge to just skip an element. However you may be able to use regex replacement to filter out the invalid content.
Another possibility would maybe to use Tidy to try to clean it up before parsing.