I am saving string into mongoDB with preset variable as
'Current time is ${time}'
After that I am retrieving somewhere else this string and would like to assign value to time
It would look something like this
const time = '15:50'
const response = result //saves string retreived from mongo
res.json({
response: response
})
But that returns 'Current time is ${time}' instead of 'Current time is 15:50'
I am aware that the string should be in `` instead of single quotes for variable to work, not sure though how to implement that as output from mongo
Anyone could point me to correct direction?
An alternative is to pass the string and parameters to a function and reduce over the parameters object:
var str = 'Current time is ${time}';
var params = { time: '13:30' };
function merge(str, params) {
return Object.keys(params).reduce((out, key) => {
return str.replace(`\${${key}}`, params[key]);
}, '');
}
console.log(merge(str, params));
And this is an example of interpolation magic, as mentioned in other answer ;) Note, than even without the evil() ;)
var time = '15:50'
var response = 'Current time is ${time}'
var converted = (_=>(new Function(`return\`${response}\`;`))())()
console.log(converted)
Interpolation is not performed on a string variable that happens to contain a template literal placeholder. In order for interpolation to happen, you must have a literal string in the code, enclosed in back ticks with a placeholder:
let time = '15:50';
let message = `Current time is ${time}`
console.log(message); // "Current time is 15:50"
If you must store strings in your database, you'll have to come up with your own mechanism for interpolating your placeholders.
Related
The output of this program is undefined instead of string name.
I am taking a date as input to the program and comparing the date with the existing dates of president array. In case if the date matches then i want to return the president name for that particular date
process.stdin.resume();
process.stdin.setEncoding('utf8');
var stdin = '';
process.stdin.on('data', function (chunk) {
//printing the value returned by presidentOnDate function
console.log(JSON.stringify(presidentOnDate(chunk)));
});
//This is presidents array
var presidents = [
{"number":32,"president":"Franklin D. Roosevelt","took_office":"1933-03-04","left_office":"1945-04-12"},
{"number":33,"president":"Harry S. Truman","took_office":"1945-04-12","left_office":"1953-01-20"},
{"number":34,"president":"Dwight D. Eisenhower","took_office":"1953-01-20","left_office":"1961-01-20"},
{"number":35,"president":"John F. Kennedy","took_office":"1961-01-20","left_office":"1963-11-22"},
{"number":36,"president":"Lyndon B. Johnson","took_office":"1963-11-22","left_office":"1969-01-20"},
{"number":37,"president":"Richard Nixon","took_office":"1969-01-20","left_office":"1974-08-09"},
{"number":38,"president":"Gerald Ford","took_office":"1974-08-09","left_office":"1977-01-20"},
{"number":39,"president":"Jimmy Carter","took_office":"1977-01-20","left_office":"1981-01-20"},
{"number":40,"president":"Ronald Reagan","took_office":"1981-01-20","left_office":"1989-01-20"},
{"number":41,"president":"George H. W. Bush","took_office":"1989-01-20","left_office":"1993-01-20"},
{"number":42,"president":"Bill Clinton","took_office":"1993-01-20","left_office":"2001-01-20"},
{"number":43,"president":"George W. Bush","took_office":"2001-01-20","left_office":"2009-01-20"},
{"number":44,"president":"Barack Obama","took_office":"2009-01-20","left_office":"2017-01-20"}
];
//PresidentOnDate function which should return a president name based on input date
function presidentOnDate(date) {
var output="";
for(var i=0;i<presidents.length;i++){
//console.log(presidents[i].took_office);
if((presidents[i].took_office)==date){
output+=presidents[i].president;
}
}
return output;
}
I think the problem is you are passing in a buffer instead of a string.
Try changing the chunk buffer to a string before passing it to presidentOnDate.
So instead of presidentOnDate(chunk) try presidentOnDate(chunk.toString())
Try this function it's working fine.
problem you facing when you take input it take \r\n also so when you compare both you get false that y output showing null.
EX:input string: "2009-01-20\r\n" compare with : took_office: "2009-01-20" => result false
EX: input string with trim: "2009-01-20" compare with : took_office: "2009-01-20" => result True
change only : (presidents[i].took_office) ==date.trim()
function presidentOnDate(date) {
var output="";
for(var i=0;i<presidents.length;i++){
if((presidents[i].took_office) ==date.trim()){
output+= presidents[i].president;
}
}
return output;
}
I have an angular function which receives a number from a GET request and then will encode that number as base 64. I am trying to use the padStart function outlined here, but when I log the string after calling the function, the string is not padded. Any ideas why?
Angular:
$scope.generateCode = function(){
var number = autogenNumber(); //Pull the number
number.then(function (result) { //Then increment up and convert
var working_str = result.toString();
console.log("The pre padded string is", working_str);
working_str.padStart(8, '1234');
console.log("The padded string is now", working_str, typeof working_str);
})
};
A string is immutable. You have to reassign
working_str = working_str.padStart(8, '1234');
Is it possible to convert mongo objectId into string.
The above pictures shows data i received and shown in console.I need id value in string form .but ObjectId is returning as object
In Database id is look like this- 565d3bf4cefddf1748d1fc5e -objectId and i need id exactly like this –
According to the Mongo documentation:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
You can check it out here: https://docs.mongodb.org/manual/reference/object-id/
So in javascript you could do something like this.
var mId = {
Timestamp:1448950573,
Machine:13565407,
Pid:1756,
Increment:8888962
};
function getId(mongoId) {
var result =
pad0(mongoId.Timestamp.toString(16), 8) +
pad0(mongoId.Machine.toString(16), 6) +
pad0(mongoId.Pid.toString(16), 4) +
pad0(mongoId.Increment.toString(16), 6);
return result;
}
function pad0(str, len) {
var zeros = "00000000000000000000000000";
if (str.length < len) {
return zeros.substr(0, len-str.length) + str;
}
return str;
}
console.log(getId(mId))
It produces "565d3b2dcefddf06dc87a282" which was not exactly the id you had, but that might just be a tweak or i was working with different data :D.
EDIT
Added a padding function so that zeros are not truncated.
Hope that helps
EDIT:
I assume you are using c# to connect to and serve documents from the mongo DB. In that case, there is a driver that also supports toString().
Here is an example using the mongo csharp driver:
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
// ...
string outputFileName; // initialize to the output file
IMongoCollection<BsonDocument> collection; // initialize to the collection to read from
using (var streamWriter = new StreamWriter(outputFileName))
{
await collection.Find(new BsonDocument())
.ForEachAsync(async (document) =>
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
var line = stringWriter.ToString();
await streamWriter.WriteLineAsync(line);
}
});
}
ORIGINAL:
These are Mongo ObjectId's and if you haven't already deserialised the document they should support a toString method that will return a hexadecimal string.
but if you want this applied to the whole document, using JSON.stringify(MogoDocument) should deserialize this for you into a plain object.
I have the code bellow to find the regular expression after %hostname and it replaces all the text correrctly for #hostname.
How do I replicate this for %Location and #Location. I can't seem to get the replication working for more than one variable.
Thanks
var host= "%hostname =(.*)"; // Perl regular expression to find title string
UltraEdit.activeDocument.top();
// Turn on regular expressions
UltraEdit.activeDocument.findReplace.regExp = true;
// Find it
UltraEdit.activeDocument.findReplace.find(host);
// Load it into a selection
var host2= UltraEdit.activeDocument.selection;
// Javascript function 'match' will match the regex within the javascript engine
// so we can extract the actual title via array
t = host2.match(host);
savehost = t[1];
UltraEdit.activeDocument.top();
UltraEdit.activeDocument.findReplace.replaceAll=true;
UltraEdit.activeDocument.findReplace.matchCase=true;
UltraEdit.activeDocument.findReplace.replace("#hostname", savehost);
Here is the UltraEdit script for this task.
The array asVariables contains the names of the variables which can be extended by you with additional strings.
if (UltraEdit.document.length > 0) // Is any file opened?
{
// Define environment for this script.
UltraEdit.insertMode();
UltraEdit.columnModeOff();
// Define a constant array of variable names which can be extended
// or modified in script code at any time to support more variables.
var asVariables = [ "hostname" , "Location" ];
// Define once all find and replace options to make the
// script independent on internal defaults of UltraEdit.
UltraEdit.perlReOn();
UltraEdit.activeDocument.findReplace.mode=0;
UltraEdit.activeDocument.findReplace.matchCase=true;
UltraEdit.activeDocument.findReplace.matchWord=false;
UltraEdit.activeDocument.findReplace.searchDown=true;
if (typeof(UltraEdit.activeDocument.findReplace.searchInColumn) == "boolean")
{
UltraEdit.activeDocument.findReplace.searchInColumn=false;
}
UltraEdit.activeDocument.findReplace.preserveCase=false;
UltraEdit.activeDocument.findReplace.replaceAll=true;
UltraEdit.activeDocument.findReplace.replaceInAllOpen=false;
// Run the code in the loop on all variables defined in the array.
for (var nVariable = 0; nVariable < asVariables.length; nVariable++)
{
// Move caret to top of the active file.
UltraEdit.activeDocument.top();
// Perl regular expression to find %variable string and assigned data.
var sSearch = "%" + asVariables[nVariable] + " *?=.*$";
UltraEdit.activeDocument.findReplace.regExp=true;
// If the variable is not found in active file,
// continue immediately with next variable.
if(!UltraEdit.activeDocument.findReplace.find(sSearch)) continue;
// Get just the string after the first equal sign from selected string.
// The replace method of JavaScript String object never modifies the
// string value itself. It creates always a new string derived from
// the current string value with the replace applied.
var sData = UltraEdit.activeDocument.selection.replace(/^.*?=(.*)$/,"$1");
// Replace all occurrences of #variable by the found data in entire file.
UltraEdit.activeDocument.top();
UltraEdit.activeDocument.findReplace.regExp=false;
sSearch = "#" + asVariables[nVariable];
UltraEdit.activeDocument.findReplace.replace(sSearch,sData);
}
}
Aanval op Vlemis (499|453) C44
This is what the string looks like. Though it's actually like this: "Aanval op variable (variable) variable
What I want to do is 1: get the coordinates (I already have this), 2 get Vlemis (first variable), get C44 (third variable) and check to see if the string is of this type.
My code:
$("#commands_table tr.nowrap").each(function(){
var text = $(this).find("input[id*='editInput']").val();
var attackername= text.match(/(?=op)[\s|\w]*(?=\()/);
var coordinates = text.match(/\(\d{1,3}\|\d{1,3}\)/);
});
Coordinates works, attackername however doesn't.
Html:
<span id="labelText[6]">Aanval op Vlemis (499|453) C44</span>
You should use one regex to take everything :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/).slice(1);
This builds
["Vlemis", "499", "453", "C44"]
If you're not sure the string is valid, test like this :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/);
if (parts) {
parts = parts.slice(1);
// do things with parts
} else {
// no match, yell at the user
}