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.
Related
I am accessing a html file using readFileSync like this
var content = fs.readFileSync("client/index.html", "utf-8");
and passing content to html.
Students.afterRemote('create', function(ctx, result, next) {
loopback.Email.send({
to: result.email,
from: "person1#something.com",
subject: "Thanks for choosing Us",
text: "text message",
html: content,
var: {
myVar1: 'a custom value'
},
headers: {
"X-My-Header": "My Custom header"
}
})
.then(function(response) {
})
.catch(function(err) {
});
}
In my html file I have this code
result.name + "<p> Your account is created successfully.Thanks for creating an account</p>"
In email it is not giving me result.name's value. It is displaying result.name. How can I access its value? Thanks
When you have something that looks like JavaScript code inside a string, then it is still just part of that string. It will not be executed as if it was JavaScript code.
var result = { name: "bar" };
var string = ` result.name + "<p> Your account is created successfully.Thanks for creating an account</p>"`;
console.log(string);
If you want to use variables, then you'll need to write them in JavaScript and not in a text file you read into a variable.
var result = { name: "bar" };
var string = `<p> Your account is created successfully.Thanks for creating an account</p>`;
var output = result.name + string;
console.log(output);
You could put placeholders in the file and then use a replace call…
var result = { name: "bar" };
var string = `<<<name>>><p> Your account is created successfully.Thanks for creating an account</p>`;
string = string.replace("<<<name>>>", result.name);
console.log(string);
… but at that stage you are creating your own template language and should probably be picking an off the shelf option like Nunjucks
var result = { name: "bar" };
var template = `{{ name }}<p> Your account is created successfully.Thanks for creating an account</p>`;
console.log(nunjucks.renderString(template, result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/nunjucks/3.0.1/nunjucks.min.js"></script>
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)
I am trying to create a loadrunner 'js' file to capture some data from a json. The json file is located on a web sever, this isn't the issue. I can successfully retrieve the json. However, I would like to return a particular value from the json text. I have attempted to do this on a local html page as follows, but I always get an error message:
Error is TypeError: Cannot read property 'Location' of undefined
Code:
<!doctype html> <head></head><script>
function getdata()
{
var jsontext = '{"Locations":{"Location":[{"#id":"3649","#latitude":"51.758","#longitude":"-1.576","#country":"England","#zoomLevel":"10","#obsZoomLevel":"5","#type":"Observing Site","#name":"Brize Norton","#geohash":"gcnyknk2h"},{"#id":"3","#latitude":"50.9503","#longitude":"-1.3567","#country":"England","#zoomLevel":"11","#type":"Airport and Heliport","#name":"Southampton Airport","#geohash":"gcp1c5hp4"}]}}';
var stringifiedjson = JSON.stringify(jsontext).replace(/#/g, '_'); //convert to JSON string
var data = JSON.parse(stringifiedjson);
json.innerHTML=data;
try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;
}
catch(err){
message.innerHTML = "(1)Error is " + err;
}
try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;
}
catch(err) {
message.innerHTML = message.innerHTML + "(2)Error is " + err;
}
try{
var newlocation0 = data.Locations.Location[0]._id;
output.innerHTML=newlocation0;
return;
}
catch(err) {
message.innerHTML = message.innerHTML + "(3)Error is " + err;
}
}
</script>
<body>
Error Messages:
<p id="message"></p>
<BR><BR>
JSON Input:
<p id="json"></p>
<BR><BR>
Output:
<p id="output"></p>
<button onclick="getdata()">Check</button>
<button onclick="location.reload();">Reload</button>
</body>
I have tried different combinations of notations of [0] and [1] but I cannot get an output for the right part of the json.
jsontext is initially a string
var jsontext = '{"Locations":{"Location":[{"#id":"3649","#latitude":"51.758","#longitude":"-1.576","#country":"England","#zoomLevel":"10","#obsZoomLevel":"5","#type":"Observing Site","#name":"Brize Norton","#geohash":"gcnyknk2h"},{"#id":"3","#latitude":"50.9503","#longitude":"-1.3567","#country":"England","#zoomLevel":"11","#type":"Airport and Heliport","#name":"Southampton Airport","#geohash":"gcp1c5hp4"}]}}';
you have wrapped that string in another string
var stringifiedjson = JSON.stringify(jsontext).replace(/#/g, '_');
the resulting string looks like this
""{\"Locations\":{\"Location\":[{\"_id\":\"3649\",\"_latitude\":\"51.758\",\"_longitude\":\"-1.576\",\"_country\":\"England\",\"_zoomLevel\":\"10\",\"_obsZoomLevel\":\"5\",\"_type\":\"Observing Site\",\"_name\":\"Brize Norton\",\"_geohash\":\"gcnyknk2h\"},{\"_id\":\"3\",\"_latitude\":\"50.9503\",\"_longitude\":\"-1.3567\",\"_country\":\"England\",\"_zoomLevel\":\"11\",\"_type\":\"Airport and Heliport\",\"_name\":\"Southampton Airport\",\"_geohash\":\"gcp1c5hp4\"}]}}""
parsing once returns the inner JSON string
var data = JSON.parse(stringifiedjson);
to get the object from string parse again
data = JSON.parse(data);
OR
there is no need for JSON.stringify in the first place, you can just use the replace method.
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, "")
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.