How I can print string in javascript - javascript

I want to print a string in following manner 'abc',21,'email' in javascript how can I do. below is my code.
var data = [];
data.push('abc');
data.push(21);
data.push('email');

Write a function to quote a string:
function quote(s) {
return typeof s === 'string' ? "'"+s+"'" : s;
}
Now map your array and paste the elements together with a comma:
data . map(quote) . join(',')
Since joining with a comma is the default way to convert an array into a string, you might be able to get away without the join in some situations:
alert (data . map(quote));
since alert converts its parameter into a string. Same with
element.textContent = data . map(quote);

if data is an array defined as
var data = [];
data.push('abc');
data.push(21);
data.push('email');
the use join() method of array to join (concatenate) the values by specifying the separator
try
alert( "'" + data.join("','") + "'" );
or
console.log( "'" + data.join("','") + "'" );
or simply
var value = "'" + data.join("','") + "'" ;
document.body.innerHTML += value;

Now data = ['abc', 21, 'email'];
So we can use forEach function
var myString = '';
data.forEach(function(value, index){
myString += typeof value === 'string' ? "'" + value + "'" : value;
if(index < data.length - 1) myString += ', ';
});
console.log(myString)
Shorter version:
myString = data.map(function(value){
return typeof value === 'string' ? "'" + value + "'" : value;
}).join(', ');
console.log(myString);
JSFiddle: https://jsfiddle.net/LeoAref/ea5fa3de/

Related

Dynamically change element name in jquery

The following is my element id and I want to update it dynamically.
invoice[46][ap_details][4][ap_header_id]
I want to update only second number, i.e. [4], like this:
invoice[46][ap_details][5][ap_header_id]
I am using below code which is updating both the values.
var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
strName = strName.replace(/[\[\]']+/g, '');
var intNumber = parseInt(strName) + 1;
return '[' + intNumber + ']';
});
Any help would be appreciated.
var strName = "invoice[46][ap_details][4][ap_header_id]";
var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
var strNewName = parts.join('[');
console.log(strNewName);
If you don't want to use arrow functions replace this line:
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
with this:
parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });
Explanation:
split will return an array like this:
[
"invoice",
"46]", // parts[1] to change this
"ap_details]",
"4]", // parts[3] to change this (and so on, you do the math)
"ap_header_id]"
]
The /^\d+/ will match any number at the begining (no need for the g modifier).
Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".
Then after you change what you want, join the parts using join with the same character you used for splitting ([).
Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.
var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];
Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/
Maybe dont use regex to build your element id. You can do its as follows as well:
var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";
var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);
console.log(name);
console.log(replaced);

javascript split('"').join('char(34)') not working for string comm"""ent

I have a string: comm"""ent.
I have to convert it to this:
value(concat("comm",char(34),char(34),char(34),"ent")).
I used value(concat(' + str.split('"').join('\",char(34),\"') + "))
But that returns:
value(concat("comm",char(34),"",char(34),"",char(34),"","ent"))
A result containing "" is not accepted by the processor.
I also tried a for loop but couldn't get that to work. How can I do this?
Just filter out empty strings:
var string = 'comm"""ent';
return 'value(concat(' + string.split(/(")/g).filter(Boolean).map(function(x) {
return x=='"' ? 'char(34)' : '"'+x+'"';
}).join(',') + '))';
Try this:
var str = "comm\"\"\"ent";
var str1 = str.split('"');
str1[0] = str1[0] + '"';
str1[str1.length-1] = ',"' + str1[str1.length-1];
str1.join(',char(34)');
This way you get:
"comm",char(34),char(34),char(34),"ent"

Javascript : expected error

I am unable to decipher the error message Expected :. It occurs when it attempts to execute the code below. I have a string of characters e.g. "Joe":"HR" being passed to it
var p = {
"\"" + m[0] + "\"" + " : " + "\"" + (m[0] = m[1]) + "\""
};
Additional code
for (var key in p)
{
if (p.hasOwnProperty(key))
{
client = selectedPackage.Elements.AddNew(key, p[key]);
client.Update();
}
}
You're defining an object, but only have a key without value, e.g. you're trying to do:
var p = {
key : value
}
But your code is only
var p = {
key
}
You have a :, but since it's inside a string (" : "), it doesn't count.
{} is an object, so it expects a value for the key:
{
"key": "value"
}
In your case, the key is "\"" + m[0] + "\"" + " : " + "\"" + (m[0] = m[1]) + "\"" (which is actually invalid, the error is a little unclear on this), so you need to specify a value as well.
I suspect you want this (from your string, which looks like JSON):
var p = { };
p[m[0]] = m[1];
You don't create an object with a variable key and value by concatenating the text of a literal. You have to use array-style assignment:
var p = {};
p[m[0]] = m[1];

passing set of data to javascript function through jquery.html()

I have 2 function in my code - makeData and displayData -.
<script type="text/javascript">
function makeData(){
var myjson = {}; var myarray = [];
for (var i = 0; i < 10; i++){
myjson[i] = "json"+i;
myarray[i] = "array"+i;
}
//when i pass myjson[1] and myarray[1] value, it's work for me
$("#mydiv").html("<input type=\"button\" value=\"display data\"
onclick=displayData(\""+myjson[0]+"\",\""+myarray[0]+"\") />");
/*but when i tried to pass the json and array object, i got problem here.
displayData() function cannot read those objects*/
$("#mydiv").html("<input type=\"button\" value=\"display data\"
onclick=displayData(\""+myjson+"\",\""+myarray+"\") />");
}
</script>
<input type="button" value="make some button" onclick="makeData()" />
<div id="mydiv"></div>
<div id="dataDisplay"></div>
how can i pass array / json object to javascript function that write using innerHTML ???
note : my purpose is to pass set of data to javascript function.
edit : i think now it is more clearly now. sorry about before..
You can convert your object or array to a string representation (JSON) to write it in the DOM (e. g. as param for a function you call onclick).
Give me 10 min to write a better example.
Here it is. It's not perfect (e. g. indexes seem to be of type "string" even if actually are "number") but it should cover most cases. Note that you cannot convert functions or references with this example:
function convertObjectToString( obj )
{
var stringRep = "{";
for ( var index in obj)
{
var cIndex;
if ( typeof index == "number" ) // int index
cIndex = index;
else // string index
cIndex = "\"" + index + "\"";
if ( typeof obj[index] == "object" )
stringRep += cIndex + ":" + convertObjectToString(
obj[index] ) + ","; // convert recursively
else if ( typeof obj[index] == "number" )
stringRep += cIndex + ":" + obj[index] + ",";
else
stringRep += cIndex + ":\"" + obj[index] + "\",";
}
// remove trailing comma (if not empty)
if ( stringRep.length > 1 )
stringRep = stringRep.substr(0, stringRep.length - 1);
stringRep += "}";
return stringRep;
}
Or better just use the JSON.stringify function! https://developer.mozilla.org/En/Using_native_JSON/
i think i've already found the answer of my problem. and this is the modified code :
function buatdata(){
var myjson={};
var myarray= [];
for(var i = 0 ; i < 10 ; i++){
myjson[i] = "json"+i;
myarray[i] = "array"+i;
}
var arraystring = myarray.toString().replace(\,\g,",");
var jsonstring = JSON.stringify(myjson).replace(\"\g,""");
/* i changed " to ' to wrap parameter that i passed in tampildata() function
and i convert those object to string first.*/
$("#tombol").html("<input type=\"button\" value=\"display\"
onclick=tampildata('"+jsonstring+"','"+arraystring+"') />");
}
function tampildata(getjson,getarray){
//i changed string that i passed back to object, so i get what i want.
var myarray = getarray.split(',');
var myjson = JSON.parse(getjson);
}
with that function, i pass array and json object through. but i still hope there is other method i can use.
because i'm affraid if my set of data very big, it can slow the proses.

Get textual (string) version of an object - displaying in the browser for debugging purposes [duplicate]

I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging.
I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.
All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.
Use Crockford's JSON.stringify like this:
var myArray = ['e', {pluribus: 'unum'}];
var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation...
Variable text would look like this:
[
"e",
{
"pluribus": "unum"
}
]
By the way, this requires nothing more than that JS file - it will work with any library, etc.
I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue.
Here is the "simple" version:
function DumpObject(obj)
{
var od = new Object;
var result = "";
var len = 0;
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
value = "'" + value + "'";
else if (typeof value == 'object')
{
if (value instanceof Array)
{
value = "[ " + value + " ]";
}
else
{
var ood = DumpObject(value);
value = "{ " + ood.dump + " }";
}
}
result += "'" + property + "' : " + value + ", ";
len++;
}
od.dump = result.replace(/, $/, "");
od.len = len;
return od;
}
I will look at improving it a bit.
Note 1: To use it, do od = DumpObject(something) and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string.
Note 2: it doesn't handle loops in references.
EDIT
I made the indented version.
function DumpObjectIndented(obj, indent)
{
var result = "";
if (indent == null) indent = "";
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
value = "'" + value + "'";
else if (typeof value == 'object')
{
if (value instanceof Array)
{
// Just let JS convert the Array to a string!
value = "[ " + value + " ]";
}
else
{
// Recursive dump
// (replace " " by "\t" or something else if you prefer)
var od = DumpObjectIndented(value, indent + " ");
// If you like { on the same line as the key
//value = "{\n" + od + "\n" + indent + "}";
// If you prefer { and } to be aligned
value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
}
}
result += indent + "'" + property + "' : " + value + ",\n";
}
return result.replace(/,\n$/, "");
}
Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one.
... I see you whipped up your own version, which is good. Visitors will have a choice.
You can use the following
<pre id="dump"></pre>
<script>
var dump = JSON.stringify(sampleJsonObject, null, 4);
$('#dump').html(dump)
</script>
In Firebug, if you just console.debug ("%o", my_object) you can click on it in the console and enter an interactive object explorer. It shows the entire object, and lets you expand nested objects.
For Node.js, use:
util.inspect(object, [options]);
API Documentation
For those looking for an awesome way to see your object, check prettyPrint.js
Creates a table with configurable view options to be printed somewhere on your doc. Better to look than in the console.
var tbl = prettyPrint( myObject, { /* options such as maxDepth, etc. */ });
document.body.appendChild(tbl);
I'm programming in Rhino and I wasn't satisfied with any of the answers that were posted here. So I've written my own pretty printer:
function pp(object, depth, embedded) {
typeof(depth) == "number" || (depth = 0)
typeof(embedded) == "boolean" || (embedded = false)
var newline = false
var spacer = function(depth) { var spaces = ""; for (var i=0;i<depth;i++) { spaces += " "}; return spaces }
var pretty = ""
if ( typeof(object) == "undefined" ) { pretty += "undefined" }
else if ( typeof(object) == "boolean" ||
typeof(object) == "number" ) { pretty += object.toString() }
else if ( typeof(object) == "string" ) { pretty += "\"" + object + "\"" }
else if ( object == null) { pretty += "null" }
else if ( object instanceof(Array) ) {
if ( object.length > 0 ) {
if (embedded) { newline = true }
var content = ""
for each (var item in object) { content += pp(item, depth+1) + ",\n" + spacer(depth+1) }
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
pretty += "[ " + content + "\n" + spacer(depth) + "]"
} else { pretty += "[]" }
}
else if (typeof(object) == "object") {
if ( Object.keys(object).length > 0 ){
if (embedded) { newline = true }
var content = ""
for (var key in object) {
content += spacer(depth + 1) + key.toString() + ": " + pp(object[key], depth+2, true) + ",\n"
}
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
pretty += "{ " + content + "\n" + spacer(depth) + "}"
} else { pretty += "{}"}
}
else { pretty += object.toString() }
return ((newline ? "\n" + spacer(depth) : "") + pretty)
}
The output looks like this:
js> pp({foo:"bar", baz: 1})
{ foo: "bar",
baz: 1
}
js> var taco
js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})
{ foo: "bar",
baz:
[ 1,
"taco",
{ blarg: "moo",
mine: "craft"
},
null,
undefined,
{}
],
bleep:
{ a: null,
b: undefined,
c: []
}
}
I've also posted it as a Gist here for whatever future changes may be required.
jsDump
jsDump.parse([
window,
document,
{ a : 5, '1' : 'foo' },
/^[ab]+$/g,
new RegExp('x(.*?)z','ig'),
alert,
function fn( x, y, z ){
return x + y;
},
true,
undefined,
null,
new Date(),
document.body,
document.getElementById('links')
])
becomes
[
[Window],
[Document],
{
"1": "foo",
"a": 5
},
/^[ab]+$/g,
/x(.*?)z/gi,
function alert( a ){
[code]
},
function fn( a, b, c ){
[code]
},
true,
undefined,
null,
"Fri Feb 19 2010 00:49:45 GMT+0300 (MSK)",
<body id="body" class="node"></body>,
<div id="links">
]
QUnit (Unit-testing framework used by jQuery) using slightly patched version of jsDump.
JSON.stringify() is not best choice on some cases.
JSON.stringify({f:function(){}}) // "{}"
JSON.stringify(document.body) // TypeError: Converting circular structure to JSON
Taking PhiLho's lead (thanks very much :)), I ended up writing my own as I couldn't quite get his to do what I wanted. It's pretty rough and ready, but it does the job I need. Thank you all for the excellent suggestions.
It's not brilliant code, I know, but for what it's worth, here it is. Someone might find it useful:
// Usage: dump(object)
function dump(object, pad){
var indent = '\t'
if (!pad) pad = ''
var out = ''
if (object.constructor == Array){
out += '[\n'
for (var i=0; i<object.length; i++){
out += pad + indent + dump(object[i], pad + indent) + '\n'
}
out += pad + ']'
}else if (object.constructor == Object){
out += '{\n'
for (var i in object){
out += pad + indent + i + ': ' + dump(object[i], pad + indent) + '\n'
}
out += pad + '}'
}else{
out += object
}
return out
}
For anyone checking this question out in 2021 or post-2021
Check out this Other StackOverflow Answer by hassan
TLDR:
JSON.stringify(data,null,2)
here the third parameter is the tab/spaces
This is really just a comment on Jason Bunting's "Use Crockford's JSON.stringify", but I wasn't able to add a comment to that answer.
As noted in the comments, JSON.stringify doesn't play well with the Prototype (www.prototypejs.org) library. However, it is fairly easy to make them play well together by temporarily removing the Array.prototype.toJSON method that prototype adds, run Crockford's stringify(), then put it back like this:
var temp = Array.prototype.toJSON;
delete Array.prototype.toJSON;
$('result').value += JSON.stringify(profile_base, null, 2);
Array.prototype.toJSON = temp;
I thought J. Buntings response on using JSON.stringify was good as well. A an aside, you can use JSON.stringify via YUIs JSON object if you happen to be using YUI. In my case I needed to dump to HTML so it was easier to just tweak/cut/paste PhiLho response.
function dumpObject(obj, indent)
{
var CR = "<br />", SPC = " ", result = "";
if (indent == null) indent = "";
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
{
value = "'" + value + "'";
}
else if (typeof value == 'object')
{
if (value instanceof Array)
{
// Just let JS convert the Array to a string!
value = "[ " + value + " ]";
}
else
{
var od = dumpObject(value, indent + SPC);
value = CR + indent + "{" + CR + od + CR + indent + "}";
}
}
result += indent + "'" + property + "' : " + value + "," + CR;
}
return result;
}
Lots of people writing code in this thread, with many comments about various gotchas. I liked this solution because it seemed complete and was a single file with no dependencies.
browser
nodejs
It worked "out of the box" and has both node and browser versions (presumably just different wrappers but I didn't dig to confirm).
The library also supports pretty printing XML, SQL and CSS, but I haven't tried those features.
A simple one for printing the elements as strings:
var s = "";
var len = array.length;
var lenMinus1 = len - 1
for (var i = 0; i < len; i++) {
s += array[i];
if(i < lenMinus1) {
s += ", ";
}
}
alert(s);
My NeatJSON library has both Ruby and JavaScript versions. It is freely available under a (permissive) MIT License. You can view an online demo/converter at:
http://phrogz.net/JS/neatjson/neatjson.html
Some features (all optional):
Wrap to a specific width; if an object or array can fit on the line, it is kept on one line.
Align the colons for all keys in an object.
Sort the keys to an object alphabetically.
Format floating point numbers to a specific number of decimals.
When wrapping, use a 'short' version that puts the open/close brackets for arrays and objects on the same line as the first/last value.
Control the whitespace for arrays and objects in a granular manner (inside brackets, before/after colons and commas).
Works in the web browser and as a Node.js module.
flexjson includes a prettyPrint() function that might give you what you want.

Categories

Resources