Remove characters from variable with Javascript - javascript

My variable looks as following:
response = "{ tradeofferid: '63341523' }"
I would like to remove all characters except for the letters and the semicolon.
I tried using the replace function but I get some errors.
function(err, response) {
if (err) {
throw err;
}
var result = response;
result = result.replace(/[{}]/g, "");
console.log(offerStatus);
res.end(result);
});
My console points at replace and the error log says: undefined is not a function
What I want to end up with is
response = "tradeofferid: 63341523"

response = { tradeofferid: '63341523' };
alert(response.tradeofferid);
for(var name in response) {
alert(name);
var value = response[name];
alert(value);
}
responseString = name + " : " + value;
alert(responseString);
You may try this but this answer is only specific to your question. This will not work if you have more than one attributes in "response" object.

response = "tradeofferid: " + JSON.parse(response)[tradeofferid]
... if you really want a string for display or something, but I'm guessing you actually just want to parse the JSON and pass the object around but haven't realized it yet.

You need to set something to be replaced in the .replace method. Try with:
var result = response.replace(/[^A-Za-z0-9\: ]/g, "")

Related

How to get JavaScript output as string in CefSharp?

I am trying to get the output of this javascript string but so far what I have tried did not work
My current code is this. response is blank what I want is 4
var task = chromiumWebBrowser1.EvaluateScriptAsync("2+2");
var response = task.Result;
MessageBox.Show(String.Format("output", response));
Any help would be great.
The EvaluateScriptAsync method returns Task<JavascriptResponse>. You can await the Task to obtain the JavascriptResponse object then get the Result or error.
JavascriptResponse response = await chromiumWebBrowser.EvaluateScriptAsync("1 + 1");
if (response.Success)
{
var onePlusOne = (int)response.Result;
}
else
{
var error = response.Message;
}

Unexpected token u in JSON at position 0 not working for async

I am fairly new to js and node.js but I have managed to get the calls going to the API and getting the necessary information. However when I was attempting to continue to raise the batter id to get the next information available. I have successfully gotten the undefined error check to work as well. But I was unable to loop through because I was trying to perform something immediately on an async function. I am now trying to make the entire function async with a 2 second delay after each run, but it is returning the following error (i'm assuming because something is undefined)
**Note: When I just get the value for i=4 and p=1 the value does exist in the API data. However it gives this error when I attempt to start with those values using this code.
error:
Unexpected token u in JSON at position 0
this is my code:
request('API Info redacted',
setTimeout (function (err, response, body) {
//do stuff below
//to get the first play of the game, set i=1 and p=0
var i = 4;
var p = 1;
// ************
var boolIn = 1;
// parse the body as JSON
var parsedBody = JSON.parse(body);
var apiResults = parsedBody.apiResults;
if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined') {
//sets the variables to the first batter of the next inning
p=0;
i = i+1;
}
//below pulls the apiResults from the body of the API request
var sportId = apiResults.sportId;
var hitName = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].name;
var fname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.firstName;
var lname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.lastName;
var outsB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.before;
var outsA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.after;
var rbis = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].runsBattedIn;
var outDifference = (outsA - outsB);
var hitB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.beforeId;
var hitA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.afterId;
var baseDifference = (hitA - hitB);
//prints the details pulled above
res.json("First Name: " + fname + ", Last Name: " + lname + ", Hit name: " + hitName + ", Outs on the play: " + outDifference + ", Rbi's: " + rbis +
", Base Sit: " + baseDifference);
//increases the batter call
p = p+1;
//below ends the setTimeout
}, 2000));
//ended request
});
setTimeout will not pass arguments to the function it calls, so body is undefined. When you pass that to JSON.parse, it will be converted to the string "undefined", which isn't a valid JSON text.
Nowhere is your code do you show any JSON coming into your program (or embedded into it). You need to have some JSON to parse before you try to parse it.

Unable to access JSON Element in Javascript via Object.property

I am unable to access a simple JSON Element from a JSON Structure that looks like:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
I get the data in JSON Format but when i do data.ACTION or data.MESSAGE i get Undefined as the output.
By doing case sensitive also, its not working( Image attached )
var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED
}, function (status) { //error detection....
alert('Something went wrong.');
});
Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}
stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"
EDITED. I first thought the error was due to parsing, given the print. -.-
Solution:
When you print the output, obj it's still a string, not an object. So it is OK at that point.
Your "undefined" property message should be replaced by MESSAGE.
Instead of console.log(obj.message); just use console.log(obj.MESSAGE);
Also. An example of parsing JSON:
var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"
obj.message property is not defined and when you try to get the property which is not defined on an object, you get undefined.
Javascript is case sensitive. You should try obj.MESSAGE instead to get the property value. Also, to check if a property exists on an object you can make use of object.hasOwnProperty([propName]) method to check if a property exists on a object or not.
EDIT 1: Try running the following code snippet. JSON data string is parsed before accessing the property.
var jsonString = "{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}";
var obj = JSON.parse(jsonString);
console.log(obj.MESSAGE);
data already is a JSON string, there's no need to JSON.stringify it (which returns a string with a JSON-encoded string literal). Parsing it into output only leads to a string again, which has no properties. You should use
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(notice the proper casing of the property name)
You can try:
var jsonObject = data.data;
console.log(jsonObject.ACTION)

string.replace not working in node.js express server

I need to read a file and replace some texts in that file with dynamic content.when i tried string.replace it is not working for the data that i read from the file.But for the string it is working.I am using node.js and express.
fs.readFile('test.html', function read(err, data) {
if (err) {
console.log(err);
}
else {
var msg = data.toString();
msg.replace("%name%", "myname");
msg.replace(/%email%/gi, 'example#gmail.com');
temp = "Hello %NAME%, would you like some %DRINK%?";
temp = temp.replace(/%NAME%/gi,"Myname");
temp = temp.replace("%DRINK%","tea");
console.log("temp: "+temp);
console.log("msg: "+msg);
}
});
Output:
temp: Hello Myname, would you like some tea?
msg: Hello %NAME%, would you like some %DRINK%?
msg = msg.replace(/%name%/gi, "myname");
You're passing a string instead of a regex to the first replace, and it doesn't match because the case is different. Even if it did match, you're not reassigning this modified value to msg. This is strange, because you're doing everything correctly for tmp.
You need to assign variable for .replace() which returns the string. In your case, you need to do like, msg = msg.replace("%name%", "myname");
Code:
fs.readFile('test.html', function read(err, data) {
if (err) {
console.log(err);
}
else {
var msg = data.toString();
msg = msg.replace("%name%", "myname");
msg = msg.replace(/%email%/gi, 'example#gmail.com');
temp = "Hello %NAME%, would you like some %DRINK%?";
temp = temp.replace(/%NAME%/gi,"Myname");
temp = temp.replace("%DRINK%","tea");
console.log("temp: "+temp);
console.log("msg: "+msg);
}
});
replace() returns a new string with the replaced substrings, so you must assign that to a variable in order to access it. It does not mutate the original string.
You would want to write the transformed string back to your file.

JSON.parse returning string instead of Array

I have a javascript Array which I am stringifying in order to store it in localstorage
console.log(request.keywords.length);
localStorage.keywords = JSON.stringify(request.keywords);
where keywords is javascript array. Here request.keywords.length returns 12 which is number of elements in array.
After retrieving it and parsing it back to JSON
var keywords = chrome.extension.getBackgroundPage().getItem("keywords");
var kjos=JSON.parse(keywords);
console.log(kjos.length);
The length returned is 342 which is the length of whole string. I tried getting type of object via constructor.name property, it gives me string instead of Array.
Any ideas what is going wrong ?
Snippets:
Background.html
function getItem(key) {
var value;
log('Get Item:' + key);
try {
value = window.localStorage.getItem(key);
}catch(e) {
log("Error inside getItem() for key:" + key);
log(e);
value = "null";
}
log("Returning value: " + value);
return value;
}
/////
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
localStorage.keywords = JSON.stringify(request.keywords);
}
);
////////////
Popup.js
var keywords = chrome.extension.getBackgroundPage().getItem("keywords");
var kjos=JSON.parse(keywords); //kjos is a string variable
/////
keywords.js
//keywordsArray is an Array object
// Message passing to background page
chrome.extension.sendRequest({message: "setKeywords", keywords: keywordsArray}, function()
{
console.log(keywordsArray);
console.log("message sent");
// The data has been sent, we can close the window now.
//window.close();
});
You need to use request like this - chrome.extension.sendRequest({message: "setKeywords"..., but for getKeywords operation. Function getItem can not be used for access to a variable of background page.

Categories

Resources