Remove all elements in an array that contain a certain character [closed] - 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 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

Related

JavaScript RegEx: How do I utilise named capture groups? [duplicate]

This question already has answers here:
Javascript: Named Capture Groups
(2 answers)
Named capturing groups in JavaScript regex?
(10 answers)
Closed last month.
I am currently working at a Plugin for RPG Maker MZ and for that, i learned how to use RegEx for analyzing the Content of a Notetag. While my first try with them was actually pretty good, i assume it didn't used the full potential of RegEx and because i need to expand the my RegEx anyway so the user has more options, i wanted to try out named capture groups for better readability and easier access for me as a developer.
Unfortionatly, i wasnt able to find out how to get the "group" object of the objects i got from the Iterator from matchAll(). So my question would be how to analyse the content of a named capture group in javascript.
Important: as far as i saw, the other questions didnt answer the question why i wasnt be able to find the right group object. also, most of the answers are with the exec function instead of the matchAll function.
The for this part relevant Code is:
const regex1new = /(?<ItemCategory>Item|Armor|Weapon)\s*:\s*(?<ID>\d+)\s*(?<Weight>w:(?<WeightFactor>\d+))?/gm;
let foundTagEntrysList = Array.from(this.enemy().meta.HellsCommonDropList.matchAll(regex1new), entry => entry[0]); //If you wanna reproduce this, just replace this.enemy().meta.HellsCommonDropList with a string
newTagsAnalyser();
function newTagsAnalyser() {
foundTagEntrysList.forEach(matchedElement => {
let Item;
let Weight;
let ID = matchedElement.groups.ID;
switch (matchedElement.groups.ItemCategory) {
case "Item":
Item = $dataItems[ID];
break;
case "Weapon":
Item = $dataWeapon[ID];
break;
case "Armor":
Item = $dataArmor[ID];
break;
default:
break;
}
if (typeof matchedElement.groups.Weight !== 'undefined'){
Weight = matchedElement.groups.WeightFactor;
}
commonItemDataMap.set(Item, Weight);
});
}
What did i expected?
That the matechedElement.group.xxx returnes the content of the group that is named xxx.
What was the result?
rmmz_managers.js:2032 TypeError: Cannot read property 'ID' of undefined

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

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"
}))

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

How to convert a string look like an array [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 2 years ago.
Improve this question
I make a get request to URL "http://cafef3.mediacdn.vn/v2/kby/ccf4d584-4b06-4370-acff-c0241b4ad0d6/kby.js". It is a javascript file and I get a string "var oc=[object_1, object_2]".
How can I create a new array based on the string above? e.g. let newArray = [object_1, object_2]
Thank!
Assuming it's for browser.. you could create a new script tag (so that the content of the javascript file will be parsed) and then assign the new variable from there.
Here is some code for reference:
const newScriptTag = document.createElement('script')
newScriptTag.textContent = content; // content is the value of the js file (var oc... )
document.body.append(newScriptTag)
let newArray = oc;
// then remove the script tag
document.body.removeChild(scriptTag)
Well, you could get rid go the prefix and suffix of your string using something like:
let result = 'var oc=["object_1", "object_2"];';
result = result.replace('var oc=','');//to remove the variable definition from the start
result = result.slice(0,-1);//to remove ';' at the end. You can use this, because strings are arrays of characters
And then use:
result = JSON.parse(result);//this should give you a nice array with your objects in it
You can find references for the methods I mentioned from a couple of different sources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
https://www.w3schools.com/jsref/jsref_replace.asp
https://www.w3schools.com/jsref/jsref_slice_array.asp
EDIT:
That last part with JSON.parse() would work if the return for your request was a valid JSON. but it's not, that's JS code, representing the definition of an object. To parse that, you could use eval(). But you should exercise caution and only use that in strings that return from trustworthy sources, since that could inadvertently execute malicious code inside your code.
That said, the last line of code to solve your problem would be something like:
result = eval(result)
console.log(result);
Thankfully, there's a better way to do it using Function() like so:
result = Function('"use strict";return (' + result + ')')
console.log(result());
You can read the reference from these two last ways of parsing code as string in here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!
Turn each object into an array using Object.entries and merge the arrays.
const obj1 = { "1": 500, "2": 15, "5": 4, "4": 480, "10": 87 };
const obj2 = { "1": 500, "2": 15, "5": 4, "4": 480, "10": 87 };
const myArray = Object.entries(obj1).concat(Object.entries(obj2));;
console.log(myArray);

Categories