I'm attempting to filter a json using regex, so that from the below just the digits from the "date" field remain. If I remove the regex from the manderleySurveyGet function then I receive the below in my terminal due to the console.log in Landing.js. However if the regex is left in I get nothing in my terminal. I tested the regex in regex101 and according to that it should work.
Terminal
SURVEY API RESULT LANDING: Array [
Object {
"_id": "6162204f1a03eed562de2e60",
"date": "10 10 2021",
"formResponse": "Survey completed",
"timeStamp": "12:05",
"userId": "email@gmail.com",
},
]
Landing.js:
manderleySurveyGet()
.then(response => {
console.log("SURVEY API RESULT LANDING:", response);
})
.catch(err => {
err.message;
});
api.js:
export async function manderleySurveyGet () {
let response = await axios.get('http://localhost:6000/');
return response.data.replace(/[\d]{1,2} [0-9]{2} [0-9]{4}/gm);
}
surveyApi.js:
let MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', function (req, res) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("manderleydb");
var query = { userId : /^(.)/ };
dbo.collection("manderleySurveyCompleted").find(query).sort({ date: 1}).limit(1)
.toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
res.status(200).send(result);
});
});
});
app.listen(6000, () => {
console.log('listening on port 6000');
});
According to MDN, replace should take at least two arguments, otherwise you'll be in trouble. In your case, you wanted:
replace(regexp, newSubstr)
But you wrote: replace(regexp). So, you got just the opposite:
If newSubstr is an empty string, then the substring given by substr, or the matches for regexp, are removed (rather then being replaced).
If you want to extract the date, the solution is to use the proper method match instead of replace, making sure it is a String.
var response = {
data:{
"_id": "6162204f1a03eed562de2e60",
"date": "10 10 2021",
"formResponse": "Survey completed",
"timeStamp": "12:05",
"userId": "email@gmail.com",
}
}
var date = JSON.stringify(response.data).match(/[\d]{2} [0-9]{2} [0-9]{4}/gm)
console.log(date)