How to match a regex across multiple strings in an array [duplicate] - javascript

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 2 years ago.
Improve this question
I need help finding the string that matches specific patterns in an array of strings
For example
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!" ]
How would I grab "FOR THE EMPEROR!!" if I want to find it by the following 2 separate scenarios:
Grab string in array which starts with "FOR"
Grab string in array that contains "EMPEROR"
They need to be ES5 or below though.

You can use the RegEx for checking the given string matching the requirements. Like this,
var regEx = /(^FOR)|(.*EMPEROR.*)/i;
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!" ]
array.filter(function(str) { return regEx.test(str) }) // ["FOR THE EMPEROR!!"]
For case-sensitive remove i in regex like: /(^FOR)|(.*EMPEROR.*)/
var regEx = /(^FOR)|(.*EMPEROR.*)/i;
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!", "For the champion", "And the EMPEROR" ]
const result = array.filter(function(str) { return regEx.test(str) })
console.log({result})

If you need to support lower version of IE, use indexOf instead of
includes.
let array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!"];
console.log(array.filter( function(el) {
return el.indexOf("EMPEROR") > -1 && el.split(" ")[0] == "FOR"
}))

Related

Remove all elements in an array that contain a certain character [closed]

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 5 months ago.
Improve this question
I have a Javascript array var array = ["1-2", "3-6", "4", "1-6", "4"] and want to remove all elements that contain the variable var m = "6", i.e. "3-6" and "1-6".
I found this line of code var newarray = array.filter(a => a !== "4"), which creates a new array that does not contain the two "4" elements. But I have not found out how to use regular expressions in order to remove all elements that CONTAIN the given variable m = "6".
I thought about something like var newarray = array.filter(a => a !== /eval("return m")/), but this does not work.
I very appreciate your help and apologize for my English :)
string.includes()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
const array = ["1-2", "3-6", "4", "1-6", "4"];
const newarray = array.filter(a => !a.includes("6"))
console.log(newarray);
regex alternative
if you need complex pattern checking, the regex is the way to go.
const array = ["1-2", "3-6", "4", "1-6", "4"];
const newarray = array.filter(a => !a.match(/6/gi))
console.log(newarray);
For example, checking uppercase and lowercase simultaneously, or multiple letters only with [abcde] or some numbers [678] etc...
without nested includes() or logic with if/else.
for learning regex you can use this https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#regular-expressions
another info:
with regex I suggest to add also the g at the end just in case /6/g
g means global (but in this case isn't important, because if there are 6 at least one time. this code will work fine (if you care about multiple 6 then use g)
also use i if you want to select also texts
in fact without i: "A" and "a" aren't the same
so with i you don't have to worry about UPPERCASE or lowercase
you can use both them by doing like this /6/gi

Javascript: Remove letters outside of two parentesis [closed]

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);

Split each string in array by semiclons [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an array-like
[
'email1#provider.com;email2#provider.com',
'email3#provider.com',
'email4#provider.com;email5#provider.com;email6#provider.com'
]
Which is the best way to map and split every semicolon on a string in order to form an array with each email separated?
If you are in a modern browser or environment, flatMap() is really nice for splitting each item and flattening into an array.
const l= [
'email1#provider.com;email2#provider.com',
'email3#provider.com',
'email4#provider.com;email5#provider.com;email6#provider.com'
]
const res = l.flatMap(s => s.split(';'))
console.log(res)
You can use reduce:
const original = [
'email1#provider.com;email2#provider.com',
'email3#provider.com',
'email4#provider.com;email5#provider.com;email6#provider.com'
];
const result = original.reduce((res, str) => {
return res.concat(str.split(';'));
}, []);
console.log(result);
In this case you can try my way:
const arr = [
"email1#provider.com;email2#provider.com",
"email3#provider.com",
"email4#provider.com;email5#provider.com;email6#provider.com",
];
const newArr = arr.join(";").split(";");
console.log(newArr);

Convert JSON to java script [closed]

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 5 years ago.
Improve this question
Can anybody provide the java script for the below JSON. I tried in many way, but could not add the field "set"
{
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
}
So your javaScript variable would be an objecthaving property/key name student of array type. Now student has two elements set a string and an object, other element is also an array, has an element of object type. This element has two properties/keys name and id.
var required = {};
required.student = [];
required.student.push("set");
var innerArray = [];
var innerObj = {};
innerObj.name = "abcd";
innerObj.id = "1234";
innerArray.push(innerObj);
required.student.push(innerArray);
document.write('<pre> ' + JSON.stringify(required,0, 3) + '</pre>');
JSON.parse(jsonString);
Is a pure JavaScript approach so long as you can require a reasonably modern browser.
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I'm not sure what you are trying to do, but...
If you just want to have the JSON object you described available in your JavaScript code, you can just put it into a variable.
var json = {
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
};
// Testing the object:
// Print the JSON object we made, as a string
console.log(JSON.stringify(json));
// Print the first item inside the 'student' array
console.log(json.student[0]);
If you instead have your JSON as a string, you can parse it to JSON object with:
var json = JSON.parse(jsonString);

How return this data in json for each? [closed]

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 5 years ago.
Improve this question
i have json values like this, i try to use for each to get the result one bye one, but it was not returning to me
"[{"id":6,"userid":13,"title":"business3","bussinessTypeid":1,"photurl":"","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":7,"userid":13,"title":"business6 arabic","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":10,"userid":13,"title":"E-commerce","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":11,"userid":8,"title":"Auto phone parts","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":19,"userid":8,"title":"التجارة الإلكترونية","bussinessTypeid":1,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":20,"userid":8,"title":"E-commerce -online shopping","bussinessTypeid":8,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":21,"userid":13,"title":"My new Business","bussinessTypeid":6,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]}]"
can anyone guide me to achive this
I think it's being treated as a string try to remove the ( " ) on the start and end of it something like:
var json = [{"id":6,"userid":13,"title":"business3","bussinessTypeid":1,"photurl":"","cntry":[{"id":"9","name":"Bahrain"}]},{"id":7,"userid":13,"title":"business6 arabic","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":10,"userid":13,"title":"E-commerce","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":11,"userid":8,"title":"Auto phone parts","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":19,"userid":8,"title":"التجارة الإلكترونية","bussinessTypeid":1,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},{"id":20,"userid":8,"title":"E-commerce -online shopping","bussinessTypeid":8,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},{"id":21,"userid":13,"title":"My new Business","bussinessTypeid":6,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]}];
Then do the iteration:
for(id in json){
alert(json[id]['id']);
}
and don't include any next line spaces are ok as long as they are separated by a comma (,)
Use parseJson()
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
$.each(data, function(key, value){
console.log(value.id, value.title);
$.each(value.cntry, function(key2, value2){
console.log(value2.id, value2.name);
})
});
Try this with jquery
var data = jQuery.parseJSON(yourJsonInString); //or this parser below
var data = JSON.parse(yourJsonInString);

Categories