print in new line in callback function in javascript - javascript

This is my code for callback function in javascript:
callback(
undefined,
body.current.weather_descriptions[0] +
"." +
"It is currently " +
body.current.temperature +
" degrees. It feels like " +
body.current.feelslike +
" degrees. There is " +
body.current.precip +
"% chance of rain."
);
My desired output is:
Varanasi, Uttar Pradesh, India
Partly cloudy.
It is currently 26 degrees.
It feels like 26 degrees.
There is 0% chance of rain.
But my output coming is:
Varanasi, Uttar Pradesh, India
Partly cloudy.It is currently 26 degrees. It feels like 26 degrees. There is 0% chance of rain.
I tried many things but not getting desired output, can you help ?

Ok to literally throw back at you the solved version of what you gave us..
callback(
undefined,
body.current.weather_descriptions[0] +
".\n" +
"It is currently " +
body.current.temperature +
" degrees.\nIt feels like " +
body.current.feelslike +
" degrees.\nThere is " +
body.current.precip +
"% chance of rain."
);

On mobile, so excuse the lack of formatting.
Add in “\n\r” each place you want to add a new line. So something like
“It is currently: “ + your.call.data + “\n\rdegrees outside”.

If you need to display this in a browser, use "<br>" tag to places where you need the new lines:
callback(
undefined,
body.current.weather_descriptions[0] +"<br>"
"." +
"It is currently " +
body.current.temperature +
" degrees." +"<br>" "It feels like " +
body.current.feelslike
" degrees." +"<br>"+ "There is " +
body.current.precip +
"% chance of rain."
);
If you need to display this in a console, use "\n" to places where you need the new lines:
callback(
undefined,
body.current.weather_descriptions[0] +"\n"
"." +
"It is currently " +
body.current.temperature +
" degrees." +"\n" "It feels like " +
body.current.feelslike
" degrees." +"\n"+ "There is " +
body.current.precip +
"% chance of rain."
);

You can insert literal newline character in a string with \n. For example:
const myString = "Hello,\nThat's a nice Tnettenba.";
console.log(myString);
Hello,
That's a nice Tnettenba.
Or, you can use backticks to create a string literal with newlines. For example:
const anotherString = `Hello,
That's a nice Tnettenba.`;
Will produce the same output as above.
Using strings delineated with backticks is helpful in this situation, as any whitespace (newlines, indents) are preserved, which is often desirable when formatting text for display. Eg.
const myTable = `
| ID | Name |
-------------------------
| 001 | Hello, World! |
| 002 | Brave New World |
`;
Will output:
| ID | Name |
-------------------------
| 001 | Hello, World! |
| 002 | Brave New World |
Note the leading spaces.

Related

why doesnt the persian word add behind a number?

i have a really strange problem in java script.
look at these codes and run the app:
const number = 200000;
const persianMoney = "تومان";
//pay attention to these lines:
console.log("way 1:");
console.log(number + persianMoney);
console.log(persianMoney + number);
console.log("way 2:");
console.log(`${number}${persianMoney}`);
console.log(`${persianMoney}${number}`);
console.log("way 3:");
console.log(String(number) + persianMoney);
console.log(persianMoney + String(number));
console.log("way 4:");
console.log(`${String(number)}${persianMoney}`);
console.log(`${persianMoney}${String(number)}`);
console.log("way 5:");
console.log(String(number + persianMoney));
console.log(String(persianMoney + number));
all of the outputs are the same!! all of the outputs are 200000تومان! but why word تومان is not behind 200000 in some outputs? even here, i cant put تومان behind 200000! but why it is like that? i cant understand it. i tested concatenation in 5 ways but none of them were correct! how can i solve this problem? thanks for helping.
As stated by Raymand Chen. My understanding is that you want to have the currency name تومان after the number 200000. To keep the Arabic/Persian word in the same direction as the Latin word i.e. in a Left-To-Right LTR direction.
One possible way to do that is to add the LTR code \u200E
const number = 200000;
const persianMoney = "تومان";
const ltr = "\u200E";
console.log(persianMoney + ltr + " " + number);

JavaScript prompt() command

I just learned about the prompt() command; I know that the prompt() command returns user input in the form of a string. I was messing with the program below, and I typed in Per "Dead" Ohlin for the male name. Why did this work and not cause any problems? "Per "Dead" Ohlin..." should have caused a problem. Does the interpreter automatically fix this by putting an escape character before the quotation marks?
let nameOfTheKiller = prompt("Type in a male name.");
let nameOfTheVictim = prompt("Type in a female name.");
let nameOfDrug = prompt("Type in the name of a drug.");
let nameOfAlchoholicBeverage = prompt("Type in the name of an alchoholic beverage.");
let story = nameOfTheKiller
story += " went to a diner, met "
story += nameOfTheVictim + ", and asked her to hangout."
story += " She said yes, so " + nameOfTheKiller + " took her home. As soon as they arrived to "
story += nameOfTheKiller + " relax-location, " + nameOfTheKiller
story += " pulled out " + nameOfDrug + " and " + nameOfAlchoholicBeverage + ". "
story += nameOfTheKiller + " and " + nameOfTheVictim
story += " started using the party favors and got really high and drunk. The party favors gave "
story += nameOfTheKiller + " auditory halucinations that comanded him to kill "
story += nameOfTheVictim + ", so he did." ;
alert("We are done asking you questions. We are generating a story for you. The story will be finished, shortly.");
document.write(story) ;
prompt is not eval - whatever you pass to it will be interpreted as a string. Typing in
Per "Dead" Ohlin
when this line runs
let nameOfTheKiller = prompt("Type in a male name.");
is like doing
let nameOfTheKiller = `Per "Dead" Ohlin`;
Any characters you include in the string you enter which happen to also be valid string delimiters in Javascript will be interpreted as those literal characters (", ', backtick), rather than as delimiters.

Why is the following way to assign a value to a JSON array not working?

I have this code:
compareList[productName] = productID + ',' + productHref;
console.log(productName + ' ' + productID + ' ' + productHref + ' ' + compareList.length);
Which logs into this (I have removed the link):
Acer Iconia B1-790 [NT.LDFEE.002] 112576 link removed for confidentiality 0
As you can see, all three variables are valid strings, but the json object still fails to assign (compareList.length logs as 0). I've been thinking and thinking but I simply can't figure it out. Any help is appreciated.
Maybe this version of adding and checking array length can be useful to you?
var compareList=[]
var productName = {productID:'saban',productHref:'http://saulic.com'};
compareList.push(productName);
console.log(compareList.length);

Formatting bible verse reference with regex in javascript

I'm trying to monospace bibleverse references so that single digit chapters or verses have a leading space.
So "4:5" becomes " 4: 5" and "3:21" becomes " 3:21".
I'm really having problems writing the regex, please help.
I've tried many variations but they essentially boil down to (^\d|\d$), (^\d{1}|\d{1}$) and (^[^0-9]\d|[^0-9]\d$) and many combinations between them
inRef = inChapter + ':' + inVerse;
var inReg = /(^[0-9]{1}|[^0-9][0-9]{1}$)/g;
inRef = inRef.replace(inReg," $1");
console.log(inRef);
Alot of the results I'm getting from my efforts turn references like "6:15" into " 6: 1 5" or " 6:1 5"
Thank you in advance.
Why a regex at all? You've already got the chapter/verse as separate data BEFORE you combined them into the x:y format, so do the formatting there while they're still seperate strings:
if (inChapter.length == 1) { inChapter = ' ' + inChapter }
inRef = inChapter + ':' + inVerse;
Using a regex for this uber-simplistic transformation is akin to nuking a city to get some dust off a shelf instead of using a feather duster.
Given the strings inChapter and inVerse, you could do something like this:
inRef = (" " + inChapter).slice(-2) + ":" + (" " + inVerse).slice(-2)
Note there are two spaces there " " and I'm assuming inChapter and inVerse are only ever 1 or 2 digits.
Edit: Since you need three digits and I assume you still want these to line up, you could do this:
var pad = " "; // this is now THREE spaces!
inRef = (pad + inChapter).slice(-pad.length) + ":" + (pad + inVerse).slice(-pad.length)
So now if you run all your inChapter and inVerse pairs through this, you should get strings that line up like this:
100:100
20:100
2:100
100: 10
100: 1
10: 10
10: 1
1: 1

How can I get a JSON object from a SQL Server table?

I have a view that I want to be converted into JSON. What is the SQL that I can use to produce on the server the JSON string needed to be returned?
--
-- Author: Thiago R. Santos --
-- Create date: Aug 3rd 2008 --
-- Description: Returns the contents of a given table --
-- in JavaScript Object Notation. --
-- Params: --
-- #table_name: the table to execute the query --
-- #registries_per_request: equivalent to "select top N * from table"
--
-- replcing N by the actual number
-- Influenced by Thomas Frank's post MySQL to JSON # January 23, 2007 --
-- Post Url: http://www.thomasfrank.se/mysql_to_json.html --
create procedure [dbo].[GetJSON]
(
#table_name varchar(50),
#registries_per_request smallint = null
)
as
begin
if((select count(*) from information_schema.tables where table_name = #table_name) > 0)
begin
declare #json varchar(max),
#line varchar(max),
#columns varchar(max),
#sql nvarchar(max),
#columnNavigator varchar(50),
#counter tinyint,
#size varchar(10)
if (#registries_per_request is null)
begin
set #size = ''
end
else
begin
set #size = 'top ' + convert(varchar, #registries_per_request)
end
set #columns = '{'
declare schemaCursor cursor
for select column_name from information_schema.columns where table_name = #table_name
open schemaCursor
fetch next from schemaCursor
into #columnNavigator
select #counter = count(*) from information_schema.columns where table_name = #table_name
while ##fetch_status = 0
begin
set #columns = #columns + '''''' + #columnNavigator + ''''':'''''' + convert(varchar, ' + #columnNavigator + ') + '''''''
set #counter = #counter - 1
if(0 != #counter)
begin
set #columns = #columns + ','
end
fetch next from schemaCursor
into #columnNavigator
end
set #columns = #columns + '}'
close schemaCursor
deallocate schemaCursor
set #json = '['
set #sql = 'select ' + #size + '''' + #columns + ''' as json into tmpJsonTable from ' + #table_name
exec sp_sqlexec #sql
select #counter = count(*) from tmpJsonTable
declare tmpCur cursor
for select * from tmpJsonTable
open tmpCur
fetch next from tmpCur
into #line
while ##fetch_status = 0
begin
set #counter = #counter - 1
set #json = #json + #line
if ( 0 != #counter )
begin
set #json = #json + ','
end
fetch next from tmpCur
into #line
end
set #json = #json + ']'
close tmpCur
deallocate tmpCur
drop table tmpJsonTable
select #json as json
end
end
I imagine this can be done, but it seems like an extremely long-winded and error-prone way of achieving the desired result.
If I were you I'd break down the problem into look at the ORM technology of your middle tier framework (ASP.NET I assume?) and then serialise to JSON again from the framework. Failing framework support (i.e. you aren't in .NET 3+) I'd still favour serialising the database to XML and then XSLT transforming the XML to JSON since XML is much much easier to work with on the server.
The name of the game is separation of concerns.
Below version is a total re-design of this concept. If I've missed something please add a note and I'll edit to adjust.
--
-- Author: Matthew D. Erwin (Snaptech, LLC)
-- Create date: May 9, 2013
-- Description: Returns the contents of a given table
-- in JavaScript Object Notation JSON -
--
-- Very notably useful for generating MOCK .json files
-- for testing or before RESTful services are completed.
--
-- This implementation:
-- *removed cursor (using FOR XML PATH(''))
-- *properly supports NULL vs quoted values
-- *supports dates in ISO 8601 - presuming UTC
-- *uses Data_Type and Is_Nullable info
-- *escapes '\'
-- *formats output with tabs/newlines
-- *can return final results as XML to bypass
-- truncation in SSMS
-- *supports schema (e.g. [dbo].[TableName]
-- *includes "recordCount" field
-- Options:
-- #table_name: the table to execute the query
-- #limit: equivalent to "select top N * from table"
-- #ssms: flag to use if executing in Sql Server Management Studio
-- to bypass result truncation limits.
--
-- Inspired primarily by the 2008 work of Thiago R. Santos which was influenced by Thomas Frank.
-- Usage: [dbo].[GetJSON] #Table_name = 'MySchema.MyTable', #limit = 50, #ssms = 0
create procedure [dbo].[GetJSON] (
#table_name varchar(max),
#limit int = null,
#ssms bit = 0
)
as
begin
declare #json varchar(max), #query varchar(max), #table_schema varchar(max) = null
if( charindex('.', #table_name) > 0 )
begin
set #table_schema = replace(replace( substring(#table_name, 0, charindex('.',#table_name)), '[', ''), ']', '')
set #table_name = replace(replace( substring(#table_name, charindex('.',#table_name) + 1,len(#table_name)), '[', ''), ']', '')
end
set #query =
'select ' + case when #limit is not null then 'top ' + cast(#limit as varchar(32)) + ' ' else '' end + '''{ '' + REVERSE(STUFF(REVERSE(''' +
CAST((SELECT ' "' + column_name + '" : ' +
case when is_nullable = 'YES'
then ''' + case when [' + column_name + '] is null then ''null'' else ' +
case when data_type like '%char%' or data_type like '%text%' then '''"'' + ' else '' end +
case when data_type like '%date%' then 'convert(varchar(23),[' + column_name + '], 126) + ''Z''' else
'replace(replace(replace(replace(cast([' + column_name + '] as varchar(max)),''\'',''\\''),''"'',''\"''),char(10),''\n''),char(13),''\n'') ' end +
case when data_type like '%char%' or data_type like '%text%' then '+ ''"''' else '' end + ' end + '''
else
case when data_type like '%char%' or data_type like '%text%' then '"' else '' end +
''' + ' +
case when data_type like '%date%' then 'convert(varchar(23),[' + column_name + '], 126) + ''Z' else
'replace(replace(replace(replace(cast([' + column_name + '] as varchar(max)),''\'',''\\''),''"'',''\"''),char(10),''\n''),char(13),''\n'') + ''' end +
case when data_type like '%char%' or data_type like '%text%' then '"' else '' end end + ',' AS [text()]
from information_schema.columns where table_name = #table_name and (#table_schema is null or table_schema = #table_schema) FOR XML PATH('') ) as varchar(max)) +
'''),1,1,'''')) + '' }'' as json into tmpJsonTable from ' + #table_name + ' with(nolock) '
exec sp_sqlexec #query
set #json =
'{' + char(10) + char(9) +
'"recordCount" : ' + Cast((select count(*) from tmpJsonTable) as varchar(32)) + ',' + char(10) + char(9) +
'"records" : ' + char(10) + char(9) + char(9) + '[' + char(10)
+ REVERSE(STUFF(REVERSE(CAST((SELECT char(9) + char(9) + json + ',' + char(10) AS [text()] FROM tmpJsonTable FOR XML PATH('')) AS varchar(max))),1,2,''))
+ char(10) + char(9) + char(9) + ']' + char(10) + '}'
drop table tmpJsonTable
if( #ssms = 1 and len(#json) > 65535 ) --deal with Sql Server Management Studio text/grid truncation
select cast('<json><![CDATA[' + #json + ']]></json>' as xml) as jsonString
else
select #json as jsonString
end
jlech answer is OK, but I don't see why you cannot generate directly off a VIEW's metadata using a technique similar to the one in this UNPIVOT answer, avoiding CURSORs and a SELECT INTO tempoary table.
Not to derail the OP's question, but I am wondering if doing this in SQL is the best / most appropriate route to take? It seems to me that this might be more easily / effectively done in code.
I was initially wondering the same thing (which is how I found this post), but after chewing on the idea for a few minutes, it seems like this might be better accomplished using a utility / extension method that takes a dataset & returns the resulting JSON string.
Granted, the OP may have good reasons for needing to go this route. I'm just thinking (typing) out loud here...

Categories