EDIT 2: I've now tested the files in a React app. JavaScript works as expected so the only actual problem seems to be that Jest snapshots inconsistently handle escape characters including in way which aren't valid JS, which could make debugging confusing. Tests still work as they should, only looking at the snapshot could be confusing.
EDIT: My question is not a duplicate of the question regarding when to use single or double quotes. I am wondering why escaping a backslash doesn't seem to work in either JSX or Jest snapshots, yet escaping a quote does.
\\ should become \ yet it appears as \\ in the official Jest example
https://github.com/facebook/jest/blob/master/examples/snapshot/tests/snapshots/link.react.test.js.snap
I'm learning Jest and looking over their example for snapshot testing. On the test entitled it properly escapes quotes, the quotes are escaped correctly, but there are parts where two backslashes are together and they're both rendered in the snapshot.
Is this some unique thing or bug related to Jest snapshots?
Here's the test
it('properly escapes quotes', () => {
const tree = renderer
.create(
<Link>
{"\"Facebook\" \\'is \\ 'awesome'"}
</Link>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
And Here's the snapshot output:
exports[`properly escapes quotes 1`] = `
<a
className="normal"
href="#"
onMouseEnter={[Function]}
onMouseLeave={[Function]}
>
"Facebook" \\'is \\ 'awesome'
</a>
`;
Why aren't the double backslashes rendered as one backslash? After all isn't that how JavaScript works?
I'd appreciate any help.
I've now tested the files in a React app. JavaScript works as expected so the only actual problem seems to be that Jest snapshots inconsistently handle escape characters including in way which aren't valid JS, which could make debugging confusing.
Tests still work as they should, only looking at the snapshot could be confusing.
I had this problem and when I used double the number of slashes in the snapshot it worked.
e.g. instead of \\, use \\\\.
Maybe when the snapshot is read in, it goes through two levels of reduction in Jest.
Related
I tried to create a Map using folium library in python3. It work's fine until i add a Marker to the map. On adding Marker the output results in just a blank HTML page.
import folium
map = folium.Map(location=[20.59,78.96], tiles = "Mapbox Bright")
folium.Marker([26.80,80.76],popup="Hey, It's Moradabad").add_to(map)
map.save("mapOutput.html")
#MCO is absolutely correct.
I like to leverage html.escape() to handle the problem characters like so
import folium
import html
map = folium.Map(location=[20.59,78.96], tiles = "Mapbox Bright")
folium.Marker([26.80,80.76],popup=html.escape("Hey, It's Moradabad")).add_to(map)
map.save("mapOutput.html")
in my experience, folium is very sensitive to single quotes (').
The reason being, folium generates javascript, and transforms your strings into javascript strings, which it encloses with single quotes. It does, however, not escape any single quotes contained in the string (not even sure if that's possible in js), so having a single quote in the string has the same effect as not closing a string in python.
Solution: Replace all single quotes in your strings with backticks (`) or (better) use #Bob Haffner's answer.
Edit: out of sheer coincidence i stumbled over another solution just now. Apparently folium.Popup has an argument parse_html. Use it like this:
folium.Marker([x,y], popup=folium.Popup("Foo'Bar",parse_html=True)).add_to(map)
however, i could not make it work without running into a unicodeescape error. nonetheless it exists, supposedly for this purpose, and might work for you.
Edit 2: As i've been told on github, this issue will be fixed in the next release. Ref: folium#962
JSON is not a subset of JavaScript. I need my output to be 100% valid JavaScript; it will be evaluated as such -- i.e., JSON.stringify will not (always) work for my needs.
Is there a JavaScript stringifier for Node?
As a bonus, it would be nice if it could stringify objects.
You can use JSON.stringify and afterwards replace the remaining U+2028 and U+2029 characters. As the article linked states, the characters can only occur in the strings, so we can safely replace them by their escaped versions without worrying about replacing characters where we should not be replacing them:
JSON.stringify('ro\u2028cks').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029')
From the last paragraph in the article you linked:
The solution
Luckily, the solution is simple: If we look at the JSON specification we see that the only place where a U+2028 or U+2029 can occur is in a string. Therefore we can simply replace every U+2028 with \u2028 (the escape sequence) and U+2029 with \u2029 whenever we need to send out some JSONP.
It’s already been fixed in Rack::JSONP and I encourage all frameworks or libraries that send out JSONP to do the same. It’s a one-line patch in most languages and the result is still 100% valid JSON.
I came across an interesting article. Which states unless until we are defining JSON we should use only single quote.
var foo = 'bar'; //Right way
var foo = "bar"; //Wrong way
Can anyone put light on this, why is it so?
Any help greatly appreciated.
The most likely reason is programmer preference / API consistency.
Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.
Here are several factors that could influence your choise:
House style: Some groups of developers already use one convention or the other.
Client-side requirements: Will you be using quotes within the strings? (See Ady's answer).
Server-side language: VB.Net people might choose to use single quotes for java-script so that the scripts can be built server-side (VB.Net uses double-quotes for strings, so the java-script strings are easy to distinguished if they use single quotes).
Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.
When using single quotes, any apostrophe needs escaping. ('Joe\'s got a cool bike.') When using double quotes, they don't. ("Joe's got a cool bike.") Apostrophes are much more common in English strings than double quotes.
Personal preference: You might thing one or other style looks better.
Please check following post that might be helpful for you When to Use Double or Single Quotes in JavaScript
First of all this is just a style guide.
You can define your ECMAScript strings the way you like them.
It is syntactically correct to use single quotes or double quotes for strings.
But according to JSON Specifications, a JSON value can be a string in double quotes, or a number, or true or false or null, or an object or an array.
Within Node.js, I am using querystring.stringify() to encode an object into a query string for usage in a URL. Values that have spaces are encoded as %20.
I'm working with a particularly finicky web service that will only accept spaces encoded as +, as used to be commonly done prior to RFC3986.
Is there a way to set an option for querystring so that it encodes spaces as +?
Currently I am simply doing a .replace() to replace all instances of %20 with +, but this is a bit tedious if there is an option I can set ahead of time.
If anyone still facing this issue, "qs" npm package has feature to encode spaces as +
qs.stringify({ a: 'b c' }, { format : 'RFC1738' })
I can't think of any library doing that by default, and unfortunately, I'd say your implementation may be the more efficient way to do this, since any other option would probably either do what you're already doing, or will use slower non-compiled pure JavaScript code.
What about asking the web service provider to follow the RFC?
https://github.com/kvz/phpjs is a node.js package that provides all the php functions. The http_build_query implementation at the time of writing this only supports urlencode (the query string includes + instead of spaces), but hopefully soon will include the enc_type parameter / rawurlencode (%20's for spaces).
See http://php.net/http_build_query.
RFC1738 (+'s) will be the default enc_type either way, so you can use it immediately for your purposes.
With the rise of node.js, multi-line strings are becoming more necessary in JavaScript.
Is there a special way to do this in Node.JS, even if it does not work in browsers?
Are there any plans or at least a feature request to do this that I can support?
I already know that you can use \n\ at the end of every line, that is not what I want.
node v4 and current versions of node
As of ES6 (and so versions of Node greater than v4), a new "template literal" intrinsic type was added to Javascript (denoted by back-ticks "`") which can also be used to construct multi-line strings, as in:
`this is a
single string`
which evaluates to: 'this is a\nsingle string'.
Note that the newline at the end of the first line is included in the resulting string.
Template literals were added to allow programmers to construct strings where values or code could be directly injected into a string literal without having to use util.format or other templaters, as in:
let num=10;
console.log(`the result of ${num} plus ${num} is ${num + num}.`);
which will print "the result of 10 plus 10 is 20." to the console.
Older versions of node
Older version of node can use a "line continuation" character allowing you to write multi-line strings such as:
'this is a \
single string'
which evaluates to: 'this is a single string'.
Note that the newline at the end of the first line is not included in the resulting string.
Multiline strings are a current part of JavaScript (since ES6) and are supported in node.js v4.0.0 and newer.
var text = `Lorem ipsum dolor
sit amet, consectetur
adipisicing
elit. `;
console.log(text);
What exactly are you looking for when you mean multiline strings.
Are you looking for something like:
var str = "Some \
String \
Here";
Which would print as "Some String Here"?
If so, keep in mind that the above is valid Javascript, but this isn't:
var str = "Some \
String \
Here";
What's the difference? A space after the \. Have fun debugging that.
As an aside to what folks have been posting here, I've heard that concatenation can be much faster than join in modern javascript vms. Meaning:
var a =
[ "hey man, this is on a line",
"and this is on another",
"and this is on a third"
].join('\n');
Will be slower than:
var a = "hey man, this is on a line\n" +
"and this is on another\n" +
"and this is on a third";
In certain cases. http://jsperf.com/string-concat-versus-array-join/3
As another aside, I find this one of the more appealing features in Coffeescript. Yes, yes, I know, haters gonna hate.
html = '''
<strong>
cup of coffeescript
</strong>
'''
Its especially nice for html snippets. I'm not saying its a reason to use it, but I do wish it would land in ecma land :-(.
Josh
In addition to accepted answer:
`this is a
single string`
which evaluates to: 'this is a\nsingle string'.
If you want to use string interpolation but without a new line,
just add backslash as in normal string:
`this is a \
single string`
=> 'this is a single string'.
Bear in mind manual whitespace is necessary though:
`this is a\
single string`
=> 'this is asingle string'
Take a look at the mstring module for node.js.
This is a simple little module that lets you have multi-line strings in JavaScript.
Just do this:
var M = require('mstring')
var mystring = M(function(){/***
Ontario
Mining and
Forestry
Group
***/})
to get
mystring === "Ontario\nMining and\nForestry\nGroup"
And that's pretty much it.
How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.
Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.
note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.
Take a look at CoffeeScript: http://coffeescript.org
It supports multi-line strings, interpolation, array comprehensions and lots of other nice stuff.
If you use io.js, it has support for multi-line strings as they are in ECMAScript 6.
var a =
`this is
a multi-line
string`;
See "New String Methods" at http://davidwalsh.name/es6-io for details and "template strings" at http://kangax.github.io/compat-table/es6/ for tracking compatibility.
Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.
CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.
I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.
If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.
Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".