Home > Mobile >  What do these expressions mean and where can i read more?
What do these expressions mean and where can i read more?

Time:08-09

Im trying to remove all the numbers inside an array which is constantly being modified, by googling i found this

var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"

Which is honestly just unreadeable, so any explanations of (/#|_/g,'') are welcome but i kept googling and also found this

let difference = arr1.filter(x => !arr2.includes(x));

which i think both do the exact same thing. Im new to JS, how do you read this? like im trying to understand it but in my head it says "filter x then if arr2 doesnt include x" and it just ends there...it seems incomplete, what happens if it doesnt include 'x'?? and also why should it include 'x' shouldnt it be 'numbers' considering 'numbers' is an array with all numbers from 0 to 9. This is so confusing to read for me, and even though i can copypaste it i dont like not understanding what im using.

If anyone can explain these expressions i'll be very grateful, if not, at least a source of where i can read about this.. since i dont even know how its called!

CodePudding user response:

The first example appears to be a RegEx (regular expression) test. str.replace(/#|_/g,'') means to replace # or _ (#|_) globally (g) with '' nothing. Take a look at a site like RegExr and read up on Regular Expressions. RegEx is an incredibly simple, yet powerful, way to match text.

The second example is a simple array filter. It filters on arr1 and filters out items not in arr2. filter is essentially a foreach loop that returns items that evaluate to true. x is the argument, being the current array item. x => !arr2.includes(x) will only be true if arr2 does not contain the current item.

A final note, the filter is using an arrow function, a function shorthand. Read up more on those here.

  • Related