JavaScript parse variable in quote [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Variable inside string without concatenation - like PHP
In PHP, double quotes has the ability to read variable, e.g.
"$foo"
But in JavaScript, you have to always use a + to read a variable so that the variable won't be inside the quote when it is read, e.g.
var foo='bar';
alert("The name's "+foo);
So, is there any workaround or method to do this? Using + all the time is quite troublesome.

Nope, that's not possible in JavaScript.
In JavaScript, variables are turned into string when put in single quotes or doubles quotes and can't be parsed. In JavaScript everything inside quotes is treated as string.
Even if you write custom parser, you will have no way to figure out if something in quotes is really a variable or an string because a variable named name can also appear in string somewhere which will create naming collisions.

No, there's no workaround, that's just how it is.
Javascript doesn't offer "string interpolation".
Personally I favour Ildar Shaimordanov's String.js module which adds a sprintf method to the string object.

Related

Are there drawbacks to using backticks for all string operations in Typescript? [duplicate]

Is there a reason (performance or other) not to use backtick template literal syntax for all strings in a javascript source file? If so, what?
Should I prefer this:
var str1 = 'this is a string';
over this?
var str2 = `this is another string`;
Code-wise, there is no specific disadvantage. JS engines are smart enough to not have performance differences between a string literal and a template literal without variables.
In fact, I might even argue that it is good to always use template literals:
You can already use single quotes or double quotes to make strings. Choosing which one is largely arbitrary, and you just stick with one. However, it is encouraged to use the other quote if your string contains your chosen string marker, i.e. if you chose ', you would still do "don't argue" instead of 'don\'t argue'. However, backticks are very rare in normal language and strings, so you would actually more rarely have to either use another string literal syntax or use escape codes, which is good.
For example, you'd be forced to use escape sequences to have the string she said: "Don't do this!" with either double or single quotes, but you wouldn't have to when using backticks.
You don't have to convert if you want to use a variable in the string in the future.
However, those are very weak advantages. But still more than none, so I would mainly use template literals.
A real but in my opinion ignorable objection is the one of having to support environments where string literals are not supported. If you have those, you would know and wouldn't be asking this question.
The most significant reason not to use them is that ES6 is not supported in all environments.
Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.
Always use template literals. In this case YAGNI is not correct. You absolutely will need it. At some point, you will have add a variable or new line to your string, at which point you will either need to change single quotes to backticks, or use the dreaded '+'.
Be careful when the values are for external use. We work with Tealium for marketing analysis, and it currently does not support ES6 template literals. Event data containing template literals aka string templates will cause the Tealium script to error.
I'm fairly convinced by other answers that there's no serious downside to using them exclusively, but one additional counterpoint is that template strings are also used in advanced "tagged template" syntax, and as illustrated in this Reddit comment, if you try to rely exclusively on JavaScript's automatic semicolon insertion or just forget to include a semicolon, you can run into parsing issues with statements that begin with a template string.
// OK (single (or double) quotes)
logger = console.log
'123'.split('').forEach(logger)
// OK (semicolon)
logger = console.log;
`123`.split('').forEach(logger)
// Not OK
logger = console.log
`123`.split('').forEach(logger) // Error

Copy Javascript-Code into PHP [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I have a problem...
I want to send a Javascript-Document-Code with a Mail-function...
The PHP-Code looks like this:
$script = '<script>
vfprintf(handle, format, args)ar hljs=new function(){function k(v){return v.replace(/&/gm,\"&\").replace(/</gm,\" ect...
</script>';
(It would be too log to post it all, 30.000 characters...)
How can I assure, that the Special-Characers (", ', \, //, ...) are escaped? :s
EDIT:
This is not a duplicate of the thread, please read it carefully!
Code in one language which emits code in another language is a notoriously difficult thing when it comes to escaping "special" characters. When that code gets upward of tens of thousands of characters then it makes a lot more sense to store it in another file which would be appropriate for that language. In this case, a .js file.
That file can be maintained as that language and not as just a literal string in PHP. This gives you things like syntax checking, debugging, testing, etc.
If the end result (such as a web page or some other displayed HTML) can simply refer to that file separately, then host the file somewhere and just send a reference to it (such as a script tag in the case of HTML). The end user's system will download the file accordingly.
If the end result needs to have this content directly embedded, then in PHP you'd read the file's contents into a string and emit that. Something like file_get_contents('yourScript.js').
Treat code as code, not as string literals.

Is there any other available in javascript, Other than $ (dollar) to use as shorthand [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Valid Characters for JavaScript Variable Names
I realize that a lot of js frameworks use $ as the short-hand like in jQuery. Is there any other symbol available in javascript, so that I can assign:
$ = function(){console.log('working')}
Aside from the dollar sign ($) and underscore (_), I don't think there are any "basic" characters that aren't taken by basic operations or string delimiters.
Edit:
Basically, this means you'll have to give your short-hand a different name if you expect your code to be used in combination with jQuery / underscore.js
However, like Deestan mentioned in the comments, you can use (pretty much) any ASCII letter as variable name, as long as it isn't taken. Then, it's just a matter of convenience.
Accents like û are relatively easy to type. The more elaborate characters could require their ASCII codes to be entered manually, which kind-of defeats the purpose of a shorthand alias.
For example, while impossible to type, this is valid js:
.
Ḣ̶̤̟͍ͦe̱̺̺̮̗̼̖ͫͭ͜͟ͅ ͚͖͙̻̈́̏ċ̨̟̖͙͈̲͇͙̬̲ͩͭ́́́o͎͓̘̭̱̩ͮ͂ͯ̿ͩͨ͂́̚̕m̬͎̜̪͋͛̏̇̊̆̋̉̒͞ę̝͕̯̯̗͋ͩ̿̈́͒̓̾͝s̸͔̜͇̔͊͢ = 'Some text';
.
(No syntax formatting on it since that breaks the effect)
Most libraries have a noConflict variable too. So, like in jQuery, you could use jQuery.fn instead of $.fn if you wanted.
There's another big library that uses _ and it's called underscore too. Never thought about it too much. But you should always think of collision when you're using common variables in global code.

Best way to generate javascript code in ruby (RoR)

I have seen some rails plugins which generate javascript code dynamically using ruby.
1.
%Q ( mixed block of javascript and ruby )
2.
<<-CODE
some mixed ruby and javascript code
CODE
Being a java developer I don't understand
what those strange looking syntax mean ?
Is one way better than the other ?
can anyone point me to proper documentation about such things ?
The first syntax is Ruby's string literal syntax. Specifically, the %Q (capital Q as opposed to lower-case) means that the string will be interpolated. eg:
%Q[Here's a string with #{a_variable} interpolated!]
Note that you can use any arbitrary characters as the open and close delimiters.
The second syntax is Ruby's heredoc syntax. The dash after the opening << indicates that Ruby will strip whitespace from the beginning of input lines contained in the heredoc block.
Ruby on Rails ships with the Prototype JavaScript framework built-in already. It also ships with JS generator helper methods which generate the Prototype code dynamically based on Ruby code.
You needn't use these if you don't want to. In fact, I rarely use them or Prototype at all, as jQuery is my JS framework of choice. So one way is not "better" than the other (except in the general sense that heredoc is better than the string literal syntax for certain cases).
In Ruby %Q provides a double quote delimited string, so:
%Q(mixed block of javascript and ruby) #=> "mixed block of javascript and ruby"
<<-CODE is what Ruby calls a Here Document, or simply heredoc. This is a mechanism for creating free format strings whilst preserving special characters such as new lines and tabs.
A heredoc is created by preceding the text with << followed by the delimiter string you wish to use to mark the end of the text.
text = <<-DOC
To be, or not to be: that is the question
William Shakespeare
DOC
When this string is printed it appears exactly as it was entered, together with all the new lines and tabs:
To be, or not to be: that is the question
William Shakespeare
%Q is the equivalent to a "" string in Ruby. But if you use such %Q-syntax, you don't need to escape double quotes.
It's a HEREDOC declaration. You also don't need to escape quotes there.
Strings in Ruby.
Here you can find the details.
Ruby with javascript

Difference between single quotes and double quotes in Javascript [duplicate]

This question already has answers here:
Are double and single quotes interchangeable in JavaScript?
(23 answers)
Closed 9 years ago.
I know that in PHP, the only difference between double quotes and single quotes is the interpretation of variable inside a string and the treatment of escape characters.
In JavaScript, I often see double quotes used in strings. Is there a particular reason for that, or are single quotes exactly the same as double quotes?
You'll want to use single quotes where you want double quotes to appear inside the string (e.g. for html attributes) without having to escape them, or vice versa. Other than that, there is no difference.
However, note that JSON (JavaScript Object Notation) only supports double quoted strings.
There is a difference in JSON - The JSON standard specifies that all key,value pairs should be in double quotes. (thanks to wulfgarpro in the comments), so I have started switching to using double-quotes as much as possible so that I don't make mistakes when dealing with JSON.
Absolutly no difference. FREE QUOTING YEEHHAAA
Unlike PHP, for which using double or single quotes changes how the
string is interpreted, there is no difference in the two syntaxes in
ECMAScript. A string using double quotes is exactly the same as a
string using single quotes. Note, however, that a string beginning
with a double quote must end with a double quote, and a string
beginning with a single quote must end with a single quote.
Nicholas C. Zakas - Professional JavaScript for Web Developers
They are the same, I usually use single quotes but thats because I am a .net developer and asp.net in particular so it aids me in distinguishing between the 2 types of strings.
I just found a difference. I'm making a mobile website, but I've mostly been testing on desktop Firefox. This works fine on Firefox:
var searchArray = searchValue.split(' '); // Split a string at the spaces.
BUT... it doesn't work on mobile Safari (iPhone 3GS running iOS 6.1). To make it work on mobile Safari, you have to use double quotes:
var searchArray = searchValue.split(" "); // Split a string at the spaces.
If you don't use double quotes, it doesn't split, it just puts the whole string into the first array element. That was a real puzzler for me and took quite a while to figure out; I dunno what even made me try switching the quotes, because I thought they were always supposed to act the same way. I haven't found anything on this problem by googling, so maybe this will help someone.

Categories

Resources