Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So, hello. I edited the entire thing.
app.get('/', async (req, res) => {
let results = await db.collection("malwarepad-website").find("6047667ff156cb8135bdaa88").toArray()
//var resultsConverted = results.toString();
//let resultsFinal = resultsConverted.split('"');
console.log(results)
res.render('index.ejs', { startText: results });
})
In the above code I want to only keep the second part of it specified better in this image: https://i.stack.imgur.com/Wi031.png
I want to create a variable containing the following:
Hello, and welcome to my website. I don't know how you found me but yo...
I already have a constant containing the search results, but it is this:
[
{
_id: 6047667ff156cb8135bdaa88,
mainPage: "Hello, and welcome to my website. I don't know how you found me but you're welcome :)."
}
]
Thanks for the understanding :)
a = a.split("\"")[1]
If you mean extracting what's inside double quotations, you have two methods:
1 - Use Regular Expressions:
You can use regular expression /.*"(.*)".*/ which tries to capture everything inside parentheses. You can use exec method. like :
const importantPart = /.*"(.*)".*/.exec(a)[1] (a is your variable)
2 - Using indexOf string methods
In JavaScript strings have two useful methods: indexOf and lastIndexOf. In addition to a substring.
You can use these to extract the important part:
a.substring(a.indexOf('"') + 1, a.lastIndexOf('"'))
There are several solutions. One could be:
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let a_splitted = a.split('"');
console.log(a_splitted[1]);
You can use regular expressions to extract the part that you need.
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let result = a.match(/\"(.*)\"/);
console.log(result[1]);
There are a lot of what-ifs though.
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let regex = /(?<=\")(.*?)(?=\")/;
let result = regex.exec(a)[0];
console.log(result);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have keyword (for example -2330) that needs to be compared with the 'values' in this string below.
"[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
Expected output needs to be true or false depending if the string has the keyword or not.
How do I check it?
I will do something like this to loop
var a = "[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
var new_a = JSON.parse(a);
var value_compare = '1574';
new_a[0]['value'].forEach(element => {
if (element[0].value == value_compare) {
//DO SOMETHING
alert('found: '+ JSON.stringify(element));
}
});
You first need to parse the JSON into an suitable JS structure. Because of the nested nature of the data you need to 1) map over the first object in your array, 2) return the value of the value property of the first object of each and finally 3) check to see if the keyword is included in the the returned array, and return true or false.
const json = '[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]';
const data = JSON.parse(json);
function doesItExist(data, keyword) {
const values = data[0].value.map(arr => arr[0].value);
return values.includes(keyword);
}
console.log(doesItExist(data, '2331'));
console.log(doesItExist(data, 'Bob'));
console.log(doesItExist(data, '1574'));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
let people = ['John','Sally','Jake','Chris'];
const logPerson = (person, index) => {
console.log('${index} - Hello ${person}');
};
people.forEach(logPerson);
it keeps printing out like this
"${index} - Hello ${person}"
how do I get it to display the names & index value code looks right as far as I can tell and from what I searched on google.
let people = ['John','Sally','Jake','Chris'];
const logPerson = (person, index) => {
console.log(`${index} - Hello ${person}`);
};
people.forEach(logPerson);
You need to use the BACKTICK, not the regular quote.
console.log(`${index} - Hello ${person}`);
If you are on the US keyboard, that symbol is just above the tab key, right beside the 1 key.
const logPerson = (person, index) => {
console.log(`${index} - Hello ${person}`);
};
people.forEach(logPerson);
In order to reference variables like this you need to use a backquote. However, if you are going to use regular quotes, you can use commas within your string if that is easier:
const logPerson = (person, index) => {
console.log(index, "- Hello", person);
};
The code above will give you the same output. You can also use the plus operator. Whichever form you choose is up to you, but use the backquote when you are trying to reference variables the way you need. Use normal quotes when attempting to reference variables normally and concatenating them within a string using the + or , operators.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In my Js script, I am using switch case but I dnt want to use it but I am not getting better alternative of this.
Here I am using Js CONSTANT as well for defining First URL & Second URL
var FIRST_URL = "/first_url.html"
var SECOND_URL = "/second_url.html"
& also passing FIRST_URL and SECOND_URL as parameter from function. That's why I used FIRST_URL with double quotes and without quotes.
Snippet :-
if(url == "DIV_ID"){
switch (url_type) {
case FIRST_URL:
case "FIRST_URL":
result = "/first_url.html";
break;
case SECOND_URL:
case "SECOND_URL":
result = "/second_url.html";
break;
default:
result = "other_url.html";
break;
}
}
Suggest something to resolve this.
You can use something like this, but add proper error checking.
Roughtly:
var arr = {};
arr['FIRST'] = 'your first url';
arr['SECOND'] = 'your second url';
result = arr[urlType];
here's an example using object literal:
var arr = {
FIRST : 'your first url',
SECOND: 'your second url'
};
console.log(arr.FIRST)
console.log(arr['SECOND'])
//for adding properties
arr.thr='third prop';
basically the resulting obj is the same to bigmike's answer, but it maybe easier to understand .
This is what is called a key-value pair and the structure is an object (JS definitions).
BTW there is nothing wrong with switch .
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
can somebody help for my code which is written in python, i want to write it in javascript but im in trouble, i dont know how.
python code
cities={}
for line in open("linnadkaugustega.txt", "r", encoding="UTF-8"):
m=line.strip().split()
abim=[word.split(":") for word in m[1:]]
cities[m[0]]={}
for couple in abim:
cities[m[0]][couple[0]]=int(couple[1])
print(cities);
and i tried in javascript but that doesen't work
function tere(){
console.log("Tere");
$.get('read.txt', function(data) {
cities={};
var lines = (data.trim()).split();
abim=[var word.split(":") for word in m[1:]]
cities[m[0]]={};
for var couple in abim
cities[m[0]][couple[0]]=couple[1];
console.log(cities);
}, 'text');
}
tere();
can somebody help me ?
You have syntax issues translating from python to js. Heres how arrays work...
if you have an array litteral in javascript
var cities = [];
Then we would add to the array by calling push
cities.push('Portland');
...
cities.push('New York');
we can then iterate over the array by calling forEach on the array object.
cities.forEach(function (city, index){
//do work on each city
console.log(city);
});
// Portland
// New York
A few things:
.split() in JS does something different than split in python when no separator is given. To split a line into words, you'll need to split on whitespaces explicitly
you're missing the for loop over the lines of the file. Python uses the iterator syntax for reading from the file, in JavaScript an ajax request loads the whole file and you'll need to split it in lines yourself.
JavaScript does not have that m[1:] syntax, you'll need to use the .slice() method instead
JavaScript does not have array/list comprehensions. You will need to use an explicit loop, or the map method of arrays
your loop syntax is too pythonic. In JavaScript, for loops need parenthesis and an index variable.
So this should do (supposed you have the jQuery library loaded and it finds the file):
$.get('read.txt', function(data) {
var cities = {};
var lines = data.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var m = line.trim().split(/\s+/);
var abim = m.slice(1).map(function(word) {
return word.split(":");
});
var obj = cities[m[0]] = {};
for (var j=0; j<abim.length; j++) {
var couple = abim[j];
obj[couple[0]] = couple[1];
}
}
console.log(cities);
}, 'text');
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a very small problem but couldn't find the solution despite of 2 hours of searching.
What I have is a simple javascript variable which is
var route_name = db.FIELD_ROUTE_NAME;
and in another javascript file
var db = {
FIELD_ROUTE_NAME: "fld_route_name",
// another js constants
};
As you can see, route_name equals to "fld_route_name" (with quotes around because it's string, I know)
Is there any way I can use this without double quotes around, like just fld_route_name ?
EDIT:
messages: { // custom messages for radio buttons and checkboxes
fld_route_name: {
required: localize("at_least_5_characters"),
},
Is there any way I can use this without double quotes
Yes, you can use simple quotes:
var db = {
FIELD_ROUTE_NAME: 'fld_route_name',
// another js constants
};
But you can't do
var db = {
FIELD_ROUTE_NAME: fld_route_name,
// another js constants
};
if fld_route_name variable is not defined.
Example:
var fld_route_name = "fld_route_name"; // the quotes still appear here
var db = {
FIELD_ROUTE_NAME: fld_route_name,
// another js constants
};
If you don't have quotes around it, then it isn't a string literal but becomes an identifier instead. In that context, an identifier is a variable.
You can avoid the quotes if you define a suitable variable first.
var fld_route_name = "fld_route_name"
var db = {
FIELD_ROUTE_NAME: fld_route_name,
// another js constants
};
Or you could use single quotes instead of double quotes.
var db = {
FIELD_ROUTE_NAME: 'fld_route_name',
// another js constants
};