By Klaus Camarena
Translation: Crazy geek
Original text: dev. To/razgandeanu…
Reproduced without permission
Here are 9 powerful JavaScript hacks.
1. Replace all
We know that string.replace() only replaces the first occurrence.
You can replace all occurrences by adding /g to the end of the regular expression.
var example = "potato potato";
console.log(example.replace(/pot/."tom"));
// "tomato potato"
console.log(example.replace(/pot/g."tom"));
// "tomato tomato"
Copy the code
2. Extract unique values
By using the Set object and the expansion operator, we can create a new array with unique values.
var entries = [1.2.2.3.4.5.6.6.7.7.8.4.2.1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]
Copy the code
3. Convert numbers to strings
We just need to use the concatenation operator with empty quotes.
var converted_number = 5 + "";
console.log(converted_number);
/ / 5
console.log(typeof converted_number);
// string
Copy the code
4. Convert strings to numbers
All we need is the + operator.
Note that it only applies to “string numbers”.
the_string = "123";
console.log(+the_string);
/ / 123
the_string = "hello";
console.log(+the_string);
// NaN
Copy the code
5. Randomly arrange the elements in the array
I do it every day
var my_list = [1.2.3.4.5.6.7.8.9];
console.log(my_list.sort(function() {
return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7]
Copy the code
6. Flatten multidimensional arrays
Just use the expansion operator.
var entries = [1[2.5], [6.7].9];
varflat_entries = [].concat(... entries);// [1, 2, 5, 6, 7, 9]
Copy the code
7. Shorten conditional statements
Let’s look at this example:
if (available) {
addToCart();
}
Copy the code
Shorten it by simply using variables and functions:
available && addToCart()
Copy the code
8. Dynamic property names
I always thought you had to declare an object before you could assign dynamic properties.
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }
Copy the code
9. Use length to adjust/empty the array
We basically overwrite the length of the array.
If we want to resize the array:
var entries = [1.2.3.4.5.6.7];
console.log(entries.length);
/ / 7
entries.length = 4;
console.log(entries.length);
/ / 4
console.log(entries);
// [1, 2, 3, 4]
Copy the code
If we want to empty the array:
var entries = [1.2.3.4.5.6.7];
console.log(entries.length);
/ / 7
entries.length = 0;
console.log(entries.length);
/ / 0
console.log(entries);
/ / []
Copy the code