Single Quote and Double Quote Append - javascript

I am trying to append a single quote and also add double quote, but it shows an error as follows
[ts] ':' expected
"id": " + ' + jsonObject["school_id"] + ' + "
expected output would be something similar as follows
"id" : "'12345'"

You can't just use ' like that.
If you want to include single quotes in the string, enclose them in a string.
const jsonObject = {"school_id": "12345"}
const obj = {"id": "'" + jsonObject["school_id"] + "'"}
console.log(obj);

You could use template strings to easily create it.
let jsonObject = {school_id:"1234"}
let s = `"id" : "'${jsonObject["school_id"]}'"`;
console.log(s)

You can simply use Template Strings:
const obj = { school_id: "1234" }
const str = `"id" : "'${obj["school_id"]}'"`;
I have not worked much with TypeScript, but looks like they are supported:
https://basarat.gitbooks.io/typescript/docs/template-strings.html

please try this to achieve expected result "id" : "'12345'"
var jsonObject = {school_id: 12345}
var a = {"id": '\'' + jsonObject['school_id'] + '\''}
console.log (a)

var school_id = '12345';
school_id = "'"+school_id+"'";
school_id = '"'+school_id+'"';
console.log(school_id);
You can do like this but make sure you know the use before doing it. don't code blindly.

Related

JSON Parse causing 'undefined' json values - Javascript

I have searched far and wide for answers to my problem but I am just not winning, I am hoping someone will be kind enough to offer me some guidance.
My below Javascript code is returning undefined json values:
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}'
var stringified = JSON.stringify(req);
console.log('stringified json ' + stringified);
//json = JSON.parse(JSON.stringify(stringified))
var json = JSON.parse(stringified );
console.log('parsed json ' + json);
//testing different ways of pulling out the data, all undefined
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json[testValue];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
The complication comes in with the backslash in the testValue property.
If I do not stringify the json first, I receive the following error:
SyntaxError: Unexpected token P in JSON at position 143
As soon as I Stringify however, and then parse, the values come back as undefined.
Does anybody perhaps know what I am doing wrong please?
Thanks
If you know that your data will never properly escape backslashes, a quick solution is the following:
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
JSON.parse(req_escaped)
Basically, make your string JSON compliant and then use the usual parsed method.
replacing the backslashes compiles. also you need to add " around testValue when you get it from the json
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}';
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
var json = JSON.parse(req_escaped);
console.log(json);
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json["testValue"];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
If you have control over the escaping process, the backslashes path should be escaped as follows:
\\ should be \\\\
The first escape escapes it in the Javascript string literal. The second escape escapes it in the JSON string literal. Credits and more details.
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\\\ProgramTest\\\\"}'
console.log(JSON.parse(req))

Reading values with different datatypes inside a string in javascript

Assume i have a string
var str = " 1, 'hello' "
I'm trying to give a function the above values found in str but as integer and string- not as one string-
for example myFunc(1,'hello')
how can i achieve that
i tried using eval(str),
but I'm getting invalid token ,
How can i solve this?
The following should work with any number of arguments.
function foo(num, str) {
console.log(num, str);
}
const input = "1, 'hel,lo'";
const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');
foo(...args);
You've almost got the right idea with eval(str) however, that isn't the thing you actually want to evaluate. If you do use eval(str), it is the same as saying eval(" 1, 'hello' ")
However, what you really want to do is:
eval("func(1, 'hello world')).
To do this you can do:
eval(func.name + '(' + str.trim() + ')');
Here we have:
func.name: The name of the function to call. You can of course hard code this. (ie just write "func(" + ...)
str.trim(): The arguments you want to pass into the given function. Here I also used .trim() to remove any additional whitespace around the string.
Take a look at the snippet below. Here I have basically written out the above line of code, however, I have used some intermediate variables to help spell out how exactly this works:
function func(myNum, myStr) {
console.log(myNum*2, myStr);
}
let str = " 1, 'hello, world'";
// Build the components for the eval:
let fncName = func.name;
let args = str.trim();
let fncStr = fncName + '(' + args + ')';
eval(fncStr);
Alternatively, if you only wish to pass in two arguments you can use .split(',') on your string to split the string based on the comma character ,.
Using split on " 1, 'hello' " will give you an array such as this one a:
let a = [" 1", "'hello'"];
Then cast your string to an integer and remove the additional quotes around your string by using .replace(/'/g, ''); (replace all ' quotes with nothing ''):
let numb = +a[0].trim(); // Get the number (convert it to integer using +)
let str = a[1].trim().replace(/'/g, ''); // get the string remove whitespace and ' around it using trim() and replace()
Now you can call your function using these two variables:
func(numb, str);
function func(myNum, myStr) {
console.log('The number times 2 is:', myNum*2, "My string is:", myStr);
}
let arguments = " 1, 'hello' ";
let arr = arguments.split(',');
let numb = +arr[0].trim(); // Argument 1
let str = arr[1].trim().replace(/'/g, ''); // Argument 2
func(numb, str);

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

How to alert a java script object in its string representation format ?

How to alert a java script object in its string representation format ?
For example, If there is a variable like this :
var a = {1:"abc",2:"xyz"};
How it can be printed out like below format using alert(a) or something like that ?
1 : abc
2 : xyz
JSON.stringify will convert your javascript object to String. Then your can replace "," with "\n" to show each field in new line. If you want to remove "{" then you can do .replace("{","")
var a ={x:"sdfd"}
alert(JSON.stringify(a).replace(",","\n"));
You can use this:
var a = {1:"abc",2:"xyz"};
var s = "";
for(var i in a){
s = s + "\n" + i + ":" + " " + a[i];
}
alert(s);
Or
alert(JSON.stringify(a));
If you want to debug objects in javascript, you must see to console.log )) try it!

how to convert to array in js?

I have this string which I want to convert to an array:
var test = "{href:'one'},{href:'two'}";
So how can I convert this to an array?:
var new = [{href:'one'},{href:'two'}];
It depends where you got it from..
If possible you should correct it a bit to make it valid JSON syntax (at least in terms of the quotes)
var test = '{"href":"one"},{"href":"two"}';
var arr = JSON.parse('[' + test + ']');
Notice the " around both keys and values.
(making directly var test = '[{"href":"one"},{"href":"two"}]'; is even better)
If you could modify the original string to be valid JSON then you could do this:
JSON.parse(test)
Valid JSON:
var test = '[{"href":"one"},{"href":"two"}]';
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj is your JSON object.
If changing the string to be valid JSON is not an option, and you fully trust this string, and its origin then I would use eval:
var test = "{href:'one'},{href:'two'}";
var arr = eval("[" + test + "]");
On that last note, please be aware that, if this string is coming from the user, it would be possible for them to pass in malicious code that eval will happily execute.
As an extremely trivial example, consider this
var test = "(function(){ window.jQuery = undefined; })()";
var arr = eval("[" + test + "]");
Bam, jQuery is wiped out.
Demonstrated here

Categories