This question already has answers here:
Javascript, Razor and Escape characters. Like apostrophe
(5 answers)
Closed 7 years ago.
I'm assigning the value of JS string variable from server side code.
Like this
var fbShareTitle = "#(ViewBag.LeadTitle as string)";
ViewBag return string value is
A "Fantastic" Lead With 'Qoute'
Now It is giving error in console
SyntaxError: missing ; before statement
I have tried this
var fbShareTitle = ("#(ViewBag.LeadTitle)").replace(/"/g, '\\"');
But now I'm getting this error.
SyntaxError: missing ; before statement
As This string will be shared on fb, So i can't modify string, like replace all " with ' e.t.c.
The reason why your code doesn't work is that Razor will generate the following:
var fbShareTitle = "A "Fantastic" Lead With 'Qoute'";
which is invalid JavaScript. You can't simply fix it by replace, since it's not the problem that your string is bad, it's that your code can't parse - replace never gets to execute. You need to fix it on serverside, where you generate the JavaScript in question, by modifying your Razor code:
var fbShareTitle = #Html.Raw(Json.Encode(ViewBag.LeadTitle as string));
Json will take care of quotes and proper escaping; Raw will make sure you don't get your < and > replaced. Extra benefit from #Html.Raw(Json.Encode(...)) mantra: you can use it to inject any kind of data that can be encoded in JSON, not only strings.
Related
This question already has answers here:
JavaScript raises SyntaxError with data rendered in Jinja template
(3 answers)
Closed 2 years ago.
I have a python backend which is connected to the website using Flask. So In the python backend I am passing a variable in this manner
return flask.render_template('index.html', code = code)
and I want to use the value of the variable in the JavaScript so I'm doing something like this
<script>
var script = {{code}}
console.log(script)
</script>
mind you I'm passing the value as a string. So For Example I'm Passing the value
TOKEN = " somevaluehere "
as a string in the variable code and when I print it out in the console, this is what I get
TOKEN = ' somevaluehere '
This is causing a lot of problems, I tried escaping the quotes with a \ but nothing works.
Maybe Something Stupid. But can someone please point it out
Jinja is escaping special characters that are control sequences for
HTML (or XML, and thus XHTML) like &, >, <, " as well as ' (see Flask Documentation).
One solution is to mark it as safe like:
{{code|safe}}
This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 3 months ago.
I am unable to retrieve a value from a json object when the string has a dash character:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789
I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?
jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:
value_template: "{{ value_json['internet-computer'].usd }}"
If you are in Linux, try using the following template to print JSON value which contains dashes '-'
jq '.["value-with-dash"]'
It worked for me.
This question already has answers here:
Are there differences between ' and " [duplicate]
(3 answers)
Closed 4 years ago.
I'm trying to detect the data type and if that data type is string then check if
it is double or single quotes.
Let say i have two strings:
var a = "hello";
var b = 'hello';
How can i detect if the string is double or single quotes in javascript???
I have tried to do so:
typeof a
i get string as output....but i don't know if that string is double or single quotes. I have also searched a alot, but can't find how is that done.
I'm trying to detect the data type and if that data type is string then check if it is double or single quotes.
You can't, that information isn't retained in any way once parsing is complete. They're both just strings. They are completely indistinguishable.
The quotes are purely a source code thing. They say "The text here isn't code, it's the content of a string." Once the string is created at runtime, it's completely irrelevant what source code created it — including the type of quotes used, or even if it was the result of evaluating something else entirely (like a template literal or a function call).
This question already has answers here:
How can I use backslashes (\) in a string?
(4 answers)
Closed 6 years ago.
Is there anyway to do this in JavaScript:
$ cat test.json
{"body":"\u0000"}
$ python3 -c 'import json; print(json.load(open("test.json", "r")))'
{'body': '\x00'}
Notice, the data above only one \ (does not need to be escaped). So you have the following situation in JavaScript:
JSON.parse('{"body":"\\u0000"}') // works
JSON.parse('{"body":"\u0000"}') // does not work
With potentially any UTF-8 data comming from a binary source (websocket), can this data be processed directly like in the first python example above?
String characters from \u0000 through \u001F are considered as control characters, and according to RFC-7159 are not allowed characters to use in JSON and must be escaped, as stated in section 7.
What you are trying to do is to put unescaped control characters into a JSON, which clearly not acceptable, you have to escape it first, non of the languages accept it, even Python.
The correct answer would be place a UTF-8 encoded value into a string containing a JSON format.
This is a correct JSON, and will be parsed by any JSON parser in any language, even in JavaScript:
{"body":"\u0000"}
This is incorrect JSON (consider the [NUL] as a NUL control character, as it cannot be represented in text):
{"body":"[NUL]"}
That's why JSON.parse('{"body":"\\u0000"}') works and JSON.parse('{"body":"\u0000"}') doesn't.
Hope, it clarifies what's wrong with your test.
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something¬interesting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something¬interesting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something¬interesting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.