Mixing variables with text in Javascript - javascript

Im trying (unsuccessfully) to prepend the following content to a div:
var entry = $('textarea').val();
var formated = '<div class="newsfeed_entry"><p>' . entry . '</p></div>';
$('#entry_container').prepend(formated);
I think the reason it isn't work is related to the way I am mixing variables and text. I looked at the documentation but I can't figure out what the issue is.

Try
var entry = $('textarea').val();
var formated = '<div class="newsfeed_entry"><p>' + entry + '</p></div>';
$('#entry_container').prepend(formated);

. is for object property lookup in JavaScript. You may have been in the PHP world for too long.
You can concatenate strings in JavaScript with the String object's concat() method or with + (it is overloaded to do arithmetic addition and string concatenation).

Related

Store data having a double quote in a javascript var

I have a var in script which has data like . But when i add this to another variable its not working.
var x = '32"';
onclick="javascript:selectSize(' + "'" + x + "'" + ');"
I want
onclick="javascript:selectSize('32"');"
But it becomes
onclick="javascript:selectSize('32"');""=""
i don't know whats happening
onclick="javascript:selectSize('32"');"
^ ^
The HTML parser will parse the attribute value before passing the value of it to the JS engine for execution.
You are using a " to delimit the attribute value.
The second " ends the attribute value.
If you want to use " as data in an attribute value delimited with " then you must express it as an entity (e.g. ").
var html_x = x.replace(/"/g, """);
Escaping becomes very painful when you start generating nested languages.
You have JavaScript embedded in HTML embedded in JavaScript.
Avoid mashing strings together to construct your DOM. Use DOM methods directly instead.
var x = '32"';
var button = document.createElement("button");
button.addEventListener("click", function (event) {
selectSize(x);
});
from comment, Make use of encode/decode URI Component as follows
var a=encodeURIComponent('abc"');
console.log(a);
console.log(decodeURIComponent(a));

Can anyone explain the meaning of this statement " var upload_file_count_text = +filenames.length + +upFiles;"

I came across a piece of code written in below format in a .js file. I am wondering what would it actually do. Just trying to understanding the purpose of this statement.
var upload_file_count_text = +filenames.length + +upFiles;
The + prefix on the variable names is the 'unary' operator. In JavaScript it is in effect shorthand for Number(). The code is changing both filenames.length and upFiles to ints from string so their values can be added instead of concatenated.
The code is equivalent to:
var upload_file_count_text = Number(filenames.length) + Number(upFiles);
In javascript prefix + is use to convert string to Int
var upload_file_count_text = +filenames.length + +upFiles;
Above code first +filenames.length which simply convert it into int type

Use String as object in javascript?

Here I am dynamically getting a string like this:
var datN="{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336";
I want to use it in HighChart api as graph data but this is not working. I have tried and got this that if the code was like this it would work:
var datN=[{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336];
so how can I convert the first variable to work like the second one? I am new to javascript please help?
UPDATE
All I want is to convert the first string to object like second one (Second one is working correctly) . I have already tries JSON.parse and eval but they didnt work. So please help?
var datArr = JSON.parse("[" + datN + "]");
This may not work across browsers because JSON.parse is not supported by all browsers. I think you could use jquery
var datArr = $.parseJSON("[" + datN + "]");
If it still does not work, you may try
var datArr = eval("[" + datN + "]");
Although this solution is not recommended.

Dynamic string wont change when changing the values that make it

http://jsfiddle.net/zzTsc/
I have a JSON that holds some values which get concatenated into a string but when I change the value of the JSON the string doesn't take the name values. How can I make the string take the new values without re-declaring the same string?
See I could easily put string = name.first + "<br />"+name.last; right below where I change the JSON value but then when I wanna edit the format of that string I'll have to change it twice.
That's not how variables work. You have to set the value of string again for it to update.
Here's an improved version so you don't have to change it twice if you want to edit something:
function generateString(name) {
return name.first + "<br />"+name.last;
}
var string = generateString(name);
​Demo
That's not going to work as you describe it, but you could declare a function which returns the appropriate string.
So instead of
string = name.first + "<br />" + name.last;
You'd have:
var stringfunction = function() {return name.first + "<br />" + name.last;}
and when you wanted to use it you'd call it:
alert(string); //old
alert(stringfunction()); //new
EDIT: I just realized you're talking about changing the format (presumably at runtime). There are a number of ways to use string formats in javascript, meaning that you could have a "format" variable used inside the stringfunction, which you could change at runtime to modify how the resulting string is formatted. It's been too long since I used one of those tools though, so I'll leave it to someone else to explain how to do string formatting in javascript.
This is because your string is a basic type and therefore holds the actual data instead of a pointer. When you change the data you think should change the string, it only changes the data. This can be seen by just re-issuing the code used to construct the string
$('#test').empty().append(name.first + "<br />"+name.last);
http://jsfiddle.net/zzTsc/4/

How to parse JSON that has inner layers using Javascript?

I can eval simple JSON with javascript.
var json = '{"amount":"50","id":"3"}';
var out = eval("{" + json + "}");
Now I am using JPA with REST and JSON-nized query result would include table name which makes
JSON having inner JSON so simple eval wouldn't work.
{"inventory":{"amount":"50","id":"3"}}
I've looked around the web for solution but can't find my case.
Should I just do string manipulation and extract {"amount":"50","id":"3"} part?
Or is there other way?
Yes, there is another (better) way! Use JSON.parse() to parse your JSON and get your object out:
var obj = JSON.parse(jsonString);
//then, for example...
var amount = obj.inventory.amount;
For older browsers (IE <8 for example) without native JSON support, include json2.js so this above still works.
Even this should work:
var json = '{"inventory":{"amount":"50","id":"3"}}';
var out = eval("{" + json + "}");
alert(out.inventory.amount);
But better to use JSON.parse
Aniway, I think that the proper way to perform a simple eval is to have the json string surrounded with parenthesis, not curly brackets...
var out = eval("(" + json + ")");
Cf. https://github.com/douglascrockford/JSON-js/blob/master/json.js :
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');

Categories

Resources