How to escape single quote in URL [duplicate] - javascript

I need to make this into a string in java:
<script type="text/javascript">document.write("<img src=\"UpArrow.png\" /> \"); </script>
Can someone help? I keep trying and it ends up like this...
return "<script type=\"text/javascript\">document.write(\"<img src=\"UpArrow.png\" /> \"); </script>";
Which doesn't work because I need to double escape the quotes before and after UpArrow.png. since it needs to be escaped in javascript and not in java.
.
.
2019 Update: If you are looking at this, god help your soul. This is awful code and if you're trying to do things this way you're doing it wrong (As others suggested to me).
The correct way to do this would be jquery or one of the zillion DOM-modifying frameworks that exist now and popping stuff into / out of the scope of the DOM.
If you are doing this, you should not look at the code above or the solutions below, but should instead go learn more, as this is a path to make spaghetti code.

Apache commons have a methods just for this in StringEscapeUtils : the escapeJavaScript method.

Looks like it was moved in Apache Commons Lang 3 to ESCAPE_ECMASCRIPT in StringEscapeUtils.
https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/src-html/org/apache/commons/lang3/StringEscapeUtils.html#line.74

It seems it moved yet again, now it is part of "commons-text" and is named:
StringEscapeUtils.escapeEcmaScript
But good it still exists.

Related

How to add single quote "'" to javascript string

So many related questions out there, but none satisfyingly answered using javascript (no jQuery).
I wish to add quotes around a variable in a string I'm building. My string itself should contain single quotes within it like so:
'{'a'}'
I can get:
'{a}'
When I try to add single quotes around the key a I get:
'{\'a\'}'
I've used both of the following syntax with the same result.
Any suggestions??
concat('\'','a','\'')
'\''+'a'+'\''
See line 39 of this code: https://repl.it/#mike_butak/LiveForHisPleasureHeReallyIsThere
Thanks!
Like this?
console.log("'{'a'}'")
To expand on this, when you are building the string, just use " around the string, and ' within the string.
Having a hard time replicating your issue! See:
var temp = '\'{\'a\'}\'';
console.log('s' + temp + 's');
I'd definitely recommend demonstrating the issue you are asking about in a console print or in a readily available editor online before posting a question!
As per your comment, updating to make it part of a variable assignment. Still unclear what the issue is!

java script failing because of white spaces caracters

I have in my views some code as this
$(".someclass").hover(function(){
$(this).append("#{render "layouts/show_some_file", title: "some_file"}");
});
The show_some_file.html.haml file consists of two nested basic divs
In my browser, I get
$(".someclass").hover(function(){
$(this).append("<div>
<div>some text</div>
</div>
");
});
On hover, I get in my chrome console SyntaxError: Unexpected token ILLEGAL. I deleted my white spaces in my console, and it worked. But how to clean the white spaces in my ruby rendering ?
I am not entirely certain it will help, but you probably should use the "<%= render ... %>" variant rather than the #{}
And since it's for javascript, the correct way would be "<%= escape_javascript(render ...) %>"
If using HAML, substitute the ERB for however the markup is written there.
Edit: might be
!= "$(this).append("#{escape_javascript(render "layouts/show_some_file", title: "some_file")}");"
Since the result of your {#render} is HTML, and although you might use it once, it might make more sense to store it in HTML, and retrieve it with JavaScript. Mimicking templating, here's an example of what I mean:
<script id="my_render" type="text/template">
#{render "layouts/show_some_file", title: "some_file"}
</script>
<script type="text/javascript">
$(document).ready(function () {
var render_content = $("#my_render").html();
$(".someclass").hover(function () {
$(this).append(render_content);
});
});
</script>
It kind of acts like a template. You use a script tag, but you set its type to something that doesn't cause it to be executed. Since script tags are never visible on a page, you would never have visual problems...unlike doing this inside of a div...the HTML is then "separate" from the rest of the page.
I'm sure there's a better solution using Ruby, but if you're outputting a partial view to JavaScript code, I'd have to ask why. It makes more sense to me to put in a "template". I understand this doesn't directly answer your immediate question, but it's an alternative :)
In fact, I got it, one of the right thing to do is :
$("someclass").hover(function(){
$(this).append("#{escape_javascript render "layouts/show_some_file", title: "some title"}");
});
The obvious thing to do is edit layouts/show_some_file & remove white space. It's not really whitespace that's the problem, but carriage returns. Javascript doesn't like multi-line strings. If I knew Ruby, I could probably write a regex that gets rid off stuff like "\r\n", which is carriage return line feed in PHP/C syntax.

Looking for regular expression that will cover every "file://"

I am try to create a regular expression for a javascript project that covers every hyperlink that starts with "file://"
Thanks :)
Hyperlinks have location properties-
you can read document.links[0].protocol from a link.
var links=document.links, L=links.length, filelinks=[];
while(L){
if(links[--L].protocol=='file:')filelinks.push(links[L].href);
}
//eg:
filelinks.join('\n')
file:///C:/webworks/gallery/gallery.html
file:///C:/webworks/library/shared/dewey.html#holmes
file:///C:/webworks/library/shared/dewey.html#twain
file:///C:/webworks/library/shared/dewey.html
Try this one
/^(file?://)?([\da-z.-]+).([a-z.]{2,6})([/\w .-])/?$/
Enjoy :)
/^file\/\/:/i.test(str)
str.match(/^file\/\/:\S+/i)
I wouldn't check for any more than the protocol, URIs are very complicated.
Here is a very thorough version developed by this guy:
(?i)\b((?:file:(?:\/{2}))(?:www\d{0,3}[.]|[a-z0-9\-]+[.])?(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
EDIT: Evidently I needed to change a few things to make it more strict. I've updated it. If you want to use the capturing groups, remove the ?: to keep a backreference.
Please use the simpler, /(file:\/{2,3}[!#$&-;=?-\[\]_a-z~]+)/

Converting plain JavaScript to jQuery

really simple question, just having a hard time actually making it work. I have a snipet of code that's javascript that I'm trying to write in jquery and can't quite get it.
effects_of_yoga_2010_INFO.style.setProperty('-webkit-transform',
'rotateZ('+effects_of_yoga_2010_DEG+'deg)');
and I had tried it as
$("#effects_of_yoga_2010_INFO").css("-webkit-transform",
"rotateZ('+effects_of_yoga_2010_DEG+'deg)");
but the jquery snippet doesn't work, I'd really appreciate any help I can get on this, I'm sure it'll be breeze for someone.
It should be:
$("#effects_of_yoga_2010_INFO").css("-webkit-transform",
"rotateZ("+effects_of_yoga_2010_DEG+"deg)");
you were mixing single quotes with double quotes.
Assuming effects_of_yoga_2010_DEG is another id of an element with a value, try:
$("#effects_of_yoga_2010_INFO").css("-webkit-transform",
"rotateZ('" + $("#effects_of_yoga_2010_DEG").val() +"'deg)");
$("#effects_of_yoga_2010_INFO").css("-webkit-transform", "rotateZ('+effects_of_yoga_2010_DEG+'deg)");
That doesn't look right. Unless this was a copy-paste error you should split the variable values from the rest of the strings the same way as the JavaScript version had done.
$("#effects_of_yoga_2010_INFO").css("-webkit-transform", "rotateZ(" + effects_of_yoga_2010_DEG + "deg)");
Of course, this is based on not knowing what effects_of_yoga_2010_DEG is. I'm assuming it simply contains the value you are looking for and can be used the same as the JavaScript version had done.

How can I make vim's taglist plugin show useful information for javascript?

I've recently abandoned mouse-driven, platform-specific GUI editors and committed entirely to vim. The experience so far has been fantastic, but I'm stuck when it comes to Javascript.
The ever-popular taglist utility (using Exuberant Ctags) has been great for everything but Javascript. With the language's overly-free form and structure, taglist could only pick up a handful of functions when I opened it up -- only those defined in the format:
function FUNCNAME (arg1, arg2) {
but no variables or function objects defined like:
var myFunc = function (arg1, arg2) {
So I googled a bit and found the following definition set for ctags, which I put in my ~/.ctags file:
--langdef=js
--langmap=js:.js
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\{/\1/,object/
--regex-js=/([A-Za-z0-9._$()]+)[ \t]*[:=][ \t]*function[ \t]*\(/\1/,function/
--regex-js=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*([^])])/\1/,function/
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\[/\1/,array/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^""]'[^'']*/\1/,string/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^'']"[^""]*/\1/,string/
After that, running ctags from the command line was fantastic. It found every function and object that I needed it to find.
The problem is that the taglist.vim plugin isn't seeing those new results. When I open my javascript file in vim and hit :TlistToggle, I get the exact same meager handful of functions I got before. I hit 'u' to update the list, with no effect.
Digging into taglist.vim, I found this:
" java language
let s:tlist_def_java_settings = 'java;p:package;c:class;i:interface;' .
\ 'f:field;m:method'
" javascript language
let s:tlist_def_javascript_settings = 'javascript;f:function'
...which implies we're only looking at one specific kind of output from the ctags utility for javascript. Unfortunately, I'm not savvy enough with taglist or vim in general (yet) to discover what change I can make to get all those wonderful ctags command-line results to show up in vim.
Help appreciated!
Got it! I dove into the taglist.vim code for awhile, and this is what I found:
taglist.vim forces ctags to use the same filetype that vim is using. So even though the ~/.ctags snippet I found via google is assigning my much-needed definitions to the new "js" language and applying it to files that end in .js, taglist is forcing ctags into using the "JavaScript" filetype that vim is using -- which is built right into ctags already.
The solution is to change the ~/.ctags file from what I've posted above to this:
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*new[ \t]+Object\(/\1/o,object/
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\{/\1/o,object/
--regex-JavaScript=/([A-Za-z0-9._$()]+)[ \t]*[:=][ \t]*function[ \t]*\(/\1/f,function/
--regex-JavaScript=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*\([^\]\)]*\)/\1/f,function/
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*new[ \t]+Array\(/\1/a,array/
--regex-JavaScript=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\[/\1/a,array/
--regex-JavaScript=/([^= ]+)[ \t]*=[ \t]*[^""]'[^'']*/\1/s,string/
--regex-JavaScript=/([^= ]+)[ \t]*=[ \t]*[^'']"[^""]*/\1/s,string/
which alters the pre-existing JavaScript language definition directly, rather than creating a new language definition within ctags. Now, when taglib forces vim's registered filetype, the new definitions are used. Also missing from the previously posted ~/.ctags lines was the "kind" letter that Al mentioned in his answer, so those are included in my updated version as well.
From there, drop the following into your ~/.vimrc to activate the new types:
let g:tlist_javascript_settings = 'javascript;s:string;a:array;o:object;f:function'
All-in-all, the new regex lines aren't perfect -- they'll definitely need some tweaking to avoid a lot of false positives, and it might be nice to separate out constants and such. But now, at least, I have the ability to do that :).
Edit: Added instructions on how to activate types without editing the plugin, and vastly improved the main ctags function regex to avoid some false-positives.
Edit 2: Added more array and object definitions to the ctags regex.
I ran into this post on a google search, and although your findings are excellent, I think we can improve them. This is the results of a bit of hacking on your solution:
.ctags
--regex-JavaScript=/^var[ \t]+([a-zA-Z0-9_$]+) = \[/\1/a,array/
--regex-JavaScript=/^var[ \t]+([a-zA-Z0-9_$]+) = \{/\1/o,object/
--regex-JavaScript=/^var[ \t]+([a-zA-Z0-9_$]+) = (^{^[)+/\1/r,var/
--regex-JavaScript=/^[ \t]*(this\.)?([A-Za-z0-9_$()]+)[ \t]*[:=][ \t]*function[ \t]*\(\)/\2/u,function/
--regex-JavaScript=/^[ \t]*function ([a-z0-9]+[A-Za-z0-9_]*)/\1/u,function/
--regex-JavaScript=/^[ \t]*([A-Za-z0-9]+)\.prototype\.([a-z0-9]+[A-Za-z0-9_]*)/\1 : \2/u,function/
--regex-JavaScript=/^[ \t]*function ([A-Z]+[A-Za-z0-9_]*)/\1/o,object/
.vimrc
let g:tlist_javascript_settings = 'javascript;r:var;s:string;a:array;o:object;u:function'
This gets rid of a few more false positives, and adds some more features in, as a tradeoff for getting rid of some of the more problematic regexes. I'll keep updating if I find I need more.
Edit: I've gotten everything working really nicely now; I feel like this result is solid. The only major deficiency is that it doesn't work on comma separated variable definitions. That seems particularly nasty. Maybe another day. :)
Note also that I changed the .vimrc. This isn't because I'm a freak; it's because somehow taglist or ctags or something has some default values set, and if you don't change it, then you get a lot of doubles where functions and vars are concerned, which really drives me insane (I pay super attention to detail.. :P )
Edit: More tweaks. It picks up on prototype function declarations now, and doesn't do some other stupid stuff.
The best-practice solution, which is also very new, neat and easy way to get JavaScript source-code browsing / tag-list in Vim, is using Mozilla's DoctorJS (formerly known as jsctags).
See my answer for this question for more info.
Enjoy. :)
I've not used javascript or taglist much, but looking through :help taglist-extend, it looks like your definitions (listed above) rename the javascript output to js, so you'll probably need something like (in your vimrc):
let tlist_js_settings = 'js;f:function;m:method'
This is assuming that the ctags 'kind' is 'f' for function and 'm' for method. Have a look at your tags file and see what the 'kind' column looks like. By way of example, my C code tags file includes this line:
ADC_CR1_AWDCH_0 .\LibraryModules\CMSIS\Headers\stm32f10x.h 2871;" d
This is a #define of a symbol ADC_CR1_AWDCH_0, which is in the listed file at line 2871. The 'd' is the ctags 'kind' for a defined name. Hopefully that will give you enough to get you going.
As an aside, I'm not sure whether the override will work correctly, so it might be worth naming your file 'myfile.mjs' and changing your langmap to js:.mjs until it's working properly. Then at least you'll know whether your problems are associated with misidentification of files or the actual parsing.
Hi thanks to Tom Frost for his question and research, I think there is a little problem with the 4th line regexp of your final answer:
--regex-JavaScript=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*\([^\]\)]*\)/\1/f,function/
Doesn't worked for me, I pulled it a bit and now works ok:
--regex-JavaScript=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*\([^\)]*\)/\1/f,function/
PD. The others answers' regexps posted here doesn't work at all at least for me :-?
To avoid duplicate entries from ctags' built in javascript support I define 'js' language as in original post and help taglist use ctags with it. I also make sure that tagnames are stripped from some less useful bits (quotes, "this.", ".prototype"). I don't use object/array/string/var regexps, but it's easy to combine my regexps with the other suggestions.
~/.ctags:
--langdef=js
--langmap=js:.js
--regex-js=/["']?(this\.)?([A-Za-z0-9_$]+)["']?((\.prototype)?(\.[A-Za-z0-9_$]+))?[ \t]*[:=][ \t]*function/\2\5/f,function/
--regex-js=/function[ \t]+([A-Za-z0-9_$]+)/\1/f,function/
~/.vimrc:
let g:tlist_javascript_settings = 'js;f:function'

Categories