r/JavaScriptTips • • May 09 '23

Best Examples of using Regex() with Match() method in JavaScript

6 Upvotes

In this article, we will look at a few examples of how to useJavaScript regex to match patterns in text.

Example 1: Matching a String

The simplest use case of regex in JavaScript is to match a specific string. In the following example, we will use the match() method to match the word "hello" in a string:

const str = "Hello, World!";
const regex = /hello/i; // i flag for case-insensitivity
const result = str.match(regex);
console.log(result); // ["Hello"]

In this example, we defined a regular expression pattern /hello/i using the RegExp() constructor. The i flag at the end makes the search case-insensitive. We then used the match() method on the string str to find the first occurrence of the pattern, which returns an array with the matching string as the first element.

Example 2: Matching Multiple Occurrences

Regular expressions can be used to match multiple occurrences of a pattern in a string. In the following example, we will use the match() method with the g
flag to find all occurrences of the word "JavaScript" in a string:

const str = "JavaScript is a programming language. JavaScript is widely used in web development.";
const regex = /JavaScript/g;
const result = str.match(regex);
console.log(result); // ["JavaScript", "JavaScript"]

In this example, we defined a regular expression pattern /JavaScript/g using the RegExp()constructor. The g flag at the end makes the search global, which means it finds all occurrences of the pattern in the string. We then used the match() method on the string str to find all occurrences of the pattern, which returns an array with all matching strings.

Example 3: Matching with Capture Groups

Capture groups are a powerful feature of regular expressions, which allow you to capture parts of the matching string. In the following example, we will use a regular expression with a capture group to match a string that contains a date in the format "YYYY-MM-DD":

const str = "Today is 2023-05-09, tomorrow is 2023-05-10.";
const regex = /(\d{4}-\d{2}-\d{2})/g;
const result = str.match(regex);
console.log(result); // ["2023-05-09", "2023-05-10"]

In this example, we defined a regular expression pattern (\d{4}-\d{2}-\d{2})/g using the RegExp() constructor. The parentheses around the \d{4}-\d{2}-\d{2} pattern create a capture group, which allows us to extract the matching date string. We then used the match() method on the string str to find all occurrences of the pattern, which returns an array with all matching strings.

Conclusion

In this article, we looked at a few examples of how to use JavaScript regex to match patterns in text, including matching a specific string, matching multiple occurrences, and using capture groups. With these examples, you should have a better understanding of how to use JavaScript regex in your web development projects.


r/JavaScriptTips • • May 02 '23

Best Way to Declare Multiple Variables in JavaScript

6 Upvotes

One of the key features of JavaScript is its ability to declare multiple variables in a single line of code. This can be a very useful technique when writing complex programs or working with large data sets.

To declare multiple variables in JavaScript, simply use the "var" keyword followed by the variable names separated by commas. For example:

var x = 5, y = 10, z = 15;

This statement declares three variables named "x", "y", and "z", and assigns them the values 5, 10, and 15, respectively. Note that each variable name is followed by an equal sign (=) and its corresponding value.

Another way to declare multiple variables is to use the "let" or "const" keywords instead of "var". The "let" keyword is used to declare variables that can be reassigned later in the code, while the "const" keyword is used to declare variables that cannot be reassigned.

let a = 20, b = 30, c = 40;
const PI = 3.14, MAX_VALUE = 100;

In the example above, the "let" keyword is used to declare three variables named "a", "b", and "c", and assign them the values 20, 30, and 40, respectively. The "const" keyword is used to declare two variables named "PI" and "MAX_VALUE", and assign them the values 3.14 and 100, respectively.

Declaring multiple variables in JavaScript can save time and make code easier to read and understand. It is especially useful when working with large data sets or writing complex algorithms. However, it is important to remember to use descriptive variable names and to avoid using global variables, which can cause problems when working with multiple functions or scripts.


r/JavaScriptTips • • Apr 30 '23

How to Iterate Object Key Value in JavaScript?

6 Upvotes

The simplest and most straightforward way to iterate over an object's key-value pairs is to use a for...in loop. This loop is designed specifically for iterating over the properties of an object, and it works by iterating over all the keys in the object and executing a block of code for each key. Here's an example:

 const myObject = {a: 1, b: 2, c: 3};

for (const key in myObject) {
  console.log(`${key}: ${myObject[key]}`);
}

In this example, we define an object called myObject with three properties: a, b, and c. We then use a for...in loop to iterate over each key in the object, and for each key, we log the key-value pair to the console.

Another way to iterate over an object's key-value pairs is to use the Object.keys() method to get an array of all the keys in the object, and then use a for...of loop to iterate over the array. Here's an example:

const myObject = {a: 1, b: 2, c: 3};

for (const key of Object.keys(myObject)) {
  console.log(`${key}: ${myObject[key]}`);
}

In this example, we use the Object.keys() method to get an array of all the keys in the myObject object. We then use a for...of loop to iterate over the array of keys, and for each key, we log the key-value pair to the console.

In conclusion, iterating over object key-value pairs is a common task in JavaScript programming, and there are several ways to achieve it. The for...in loop, Object.keys() method with for...of loop, and Object.entries() method with for...of loop are all great options to choose from depending on your use case.


r/JavaScriptTips • • Apr 28 '23

What is JavaScript shorthand if?

6 Upvotes

JS shorthand if is a condensed way of writing an if-else statement in JavaScript. It’s a useful technique that can help you write more efficient and readable code.

The shorthand if is also known as the ternary operator, and it looks like this:

condition ? valueIfTrue : valueIfFalse

The condition is evaluated first. If the condition is true, then the value of valueIfTrue is returned. Otherwise, the value of valueIfFalse is returned.

Here’s an example:

const age = 25;
const allowed = age >= 18 ? "Yes" : "No";
console.log(allowed); // Output: "Yes"

In this example, the age variable is assigned a value of 25. Then, the allowed variable is assigned the result of the ternary operator. The condition is age >= 18, which evaluates to true. Therefore, the value of valueIfTrue is "Yes".

Using the shorthand if can help you write more concise code. It’s especially useful when you need to assign a value to a variable based on a condition. Instead of writing an if-else statement, you can use the shorthand if to achieve the same result with less code.

However, it’s important to use the shorthand if judiciously. If the condition and the values are complex, it can make the code harder to read and understand. In those cases, it’s better to use a regular if-else statement.

In conclusion, the JS shorthand if is a powerful tool in your JavaScript toolkit. It’s a simple and elegant way of writing conditional statements, and it can help you write cleaner and more efficient code. Just make sure to use it appropriately and in moderation.


r/JavaScriptTips • • Apr 14 '23

How to Filter Array of Objects by Value in JavaScript

6 Upvotes

If you're working with arrays of objects in JavaScript, you may find yourself needing to filter the array based on a specific value. Luckily, JavaScript provides us with a built-in method to do just that: Array.filter() . In this article, we'll explore how to to filter an array of objects by value.

Let's say we have an array of objects representing different people, with properties like "name", "age", and "occupation". We want to filter this array to only include people who are over the age of 30. Here's how we could do it:

const people = [
  { name: "Alice", age: 25, occupation: "Engineer" },
  { name: "Bob", age: 35, occupation: "Teacher" },
  { name: "Charlie", age: 42, occupation: "Doctor" },
  { name: "Dave", age: 28, occupation: "Writer" },
];

const filteredPeople = people.filter((person) => person.age > 30);

console.log(filteredPeople);
// Output: [{ name: "Bob", age: 35, occupation: "Teacher" }, { name: "Charlie", age: 42, occupation: "Doctor" }]

Here, we're using the filter() method on the people array, and passing in a function as an argument. This function takes each object in the array as its argument (which we've named person), and returns a boolean value indicating whether that object should be included in the filtered array.

In this case, we're using a simple comparison to check if the person's age is greater than 30. If it is, the function returns true, and the person is included in the filtered array. If not, the function returns false, and the person is excluded.

This is just one example of how you can use Array.filter() to filter an array of objects by value. Depending on your specific use case, you may need to use more complex comparison logic or filter on different properties of the objects in the array. But with Array.filter( as your tool, you'll be able to filter your arrays with ease.


r/JavaScriptTips • • Mar 14 '23

What am I doing wrong?

Post image
6 Upvotes

r/JavaScriptTips • • Feb 24 '23

JavaScript ES6 (ECMAScript 2015) topics

6 Upvotes

JavaScript ES6 (ECMAScript 2015) is an important update to the language that introduced many new features and syntax improvements. Here are some key topics you may want to review to prepare for working with ES6:

  1. Arrow functions: Arrow functions provide a concise way to define functions and lexically bind the this value.

  2. Template literals: Template literals allow for more flexible string interpolation and multiline strings.

  3. Let and const: Let and const are block-scoped variables that provide more predictable variable scoping and behavior.

  4. Destructuring assignment: Destructuring allows you to extract values from arrays and objects into variables.

  5. Default parameters: Default parameters allow you to define default values for function parameters.

  6. Rest parameters: Rest parameters allow you to capture multiple function arguments into a single array parameter.

  7. Spread operator: The spread operator allows you to spread an array into individual arguments or combine multiple arrays.

  8. Classes: Classes provide a more familiar syntax for defining object-oriented classes and inheritance.

  9. Promises: Promises provide a way to handle asynchronous operations and avoid callback hell.

  10. Modules: ES6 modules provide a more standardized and modular approach to organizing and sharing code.

Learn more about Javascript topics: https://www.weeklywoo.com/top-javascript-interview-questions-and-answers-mostly-asked/

You may also want to review other features such as generators, symbols, and the new for...of
loop. Additionally, it's important to be familiar with the basics of JavaScript such as variables, functions, arrays, and objects.

I hope this helps! Let me know if you have any other questions.


r/JavaScriptTips • • Dec 06 '22

Loops in Javascript (For, For in, For of, For each and while)

Thumbnail
medium.com
6 Upvotes

r/JavaScriptTips • • Nov 22 '22

Leetcode for frontend series (part 8 of 97 is out)

6 Upvotes

This series will include 97 parts out of which 8 have been released. This series will contain a lot of unique questions with in-depth explanations that will strengthen your JavaScript knowledge and help you become a better JavaScript developer. (ALL FOR FREE)

link - https://www.youtube.com/playlist?list=PLOfzxGau1V5Ud9d3preQZnn9lYhUsRgYn


r/JavaScriptTips • • Oct 24 '22

Any way to speed up typing Javascript fuctions in VSCode?

6 Upvotes

I am looking for a hotkey that moves the cursor to the outside of the () and {} when first creating functions. I know the right arrow key does this but it is kind of a pain to do, I was hoping Tab did this but it does not. Anyone know if this exists or is right arrow key the best there is? Thanks!


r/JavaScriptTips • • Oct 07 '22

Need an advice about how to get better with JavaScript

6 Upvotes

What's up everybody :) I have a question. I'm front end developer for the last 3 years, I'm 20 years old. I have strong knowledge of HTML/CSS and Css frameworks, and mid range knowledge of JavaScript. My question is, can someone please tell me how to get better at JavaScript. I did a lot of project with JavaScript included, but still I think I only know maybe 30% of it. Anyone have any advice what should I do? I'm constatly doing projects, but I have a feeling I'm not progressing at all. Please dear programmers.


r/JavaScriptTips • • Sep 16 '22

Heart rain effect using HTML, CSS and JavaScript

Thumbnail reddit.com
6 Upvotes

r/JavaScriptTips • • Aug 16 '22

is there anything that I can passively listen to to help learn while at work?

6 Upvotes

Looking for something to just be in my ear while I'm working. Idk if anything worthwhile exists or if watching is necessary to learn. I know some basics already if that matters.


r/JavaScriptTips • • Jul 07 '22

Why isn’t my code working even though I have set the width for the element?

Thumbnail
gallery
6 Upvotes

r/JavaScriptTips • • Apr 26 '22

Dynamic Progress Bar using JavaScript

6 Upvotes

I built a dynamic progress bar using JavaScript which changes based on the value and max value the user inputs. If any of you are curious regarding how to build this, here's a short 15 min tutorial
Link: https://www.youtube.com/watch?v=Ll5f0jGIqa4


r/JavaScriptTips • • Oct 29 '21

Using JavaScript To Build A Screen Recording App Easy And Fast

Thumbnail
medium.com
6 Upvotes

r/JavaScriptTips • • Jun 24 '21

4 Ways To Write For Loops in JavaScript

6 Upvotes

JavaScript, as a programming language, is not static but constantly evolving. The expansion of the for loop syntax is a great example to show it.

This article will summarize the four ways to write JavaScript for loops in the order of their appearance. After reading, you can use them properly as an expert.


r/JavaScriptTips • • Jun 20 '21

3 Uses of the Three Dots in JavaScript

Thumbnail
medium.com
6 Upvotes

r/JavaScriptTips • • Mar 30 '21

Build high order operators in Reactive Programming - free

6 Upvotes

Build high order operators in Reactive Programming

  • Build the merge observable

  • Build the mapTo operator

  • Build the scan operator

https://app.hackjam.io/hj-details/reactive-programming-course-part-2

Register here for Q&A on 6 April:
https://us02web.zoom.us/meeting/register/tZErceytrDspH9H9_AuBWZPr2Ot_FrBH2Uwh


r/JavaScriptTips • • Jan 06 '21

Learning JavaScript DOM 🔥

Thumbnail
tutorialstonight.com
6 Upvotes

r/JavaScriptTips • • Dec 19 '20

How to make the screen movable by clicking and dragging?

6 Upvotes

So in some videogames, especially strategy games, you can move your screen around by clicking and dragging your mouse. I plan on having a map (png file) on the screen which will be larger than the actual display at least in most cases. Instead of using the scroll bars to move around the map and having to click and drag each scroll bar to get where you are going, I am wondering if anyone knows how could allow the user to click on the image and drag the mouse around to move the window to view other parts of the image on their screen. Basically how can I make it so the user can click on an element in the dom and drag their mouse around to move the screen without having to touch the X and Y axis scroll bars?


r/JavaScriptTips • • Oct 17 '20

javascript array: create array, add element, access element, change element and find length of array🔥🖥️

Thumbnail
gallery
6 Upvotes

r/JavaScriptTips • • Oct 09 '25

“Promise.all vs allSettled vs race vs any” — Which one do you actually use in real projects?

5 Upvotes

I’ve seen this question (and mistake) pop up so many times:
A dev wraps multiple API calls inside Promise.all… one fails… 💥 and suddenly everything crashes.

The truth?
Not all Promise methods behave the same — and understanding their differences can save you hours of debugging and weird async bugs.

Here’s the quick rundown I shared in my latest deep-dive article 👇

  • Promise.all → All or nothing. If one fails, everyone fails.

  • Promise.allSettled → Waits for all, even if some fail. Perfect for logging or partial UI updates.

  • Promise.race → First to settle (success or failure) wins. Great for timeouts.

  • Promise.any → First success wins. Perfect for redundant or fallback API calls.

What I found fascinating while writing it is how differently they behave in the event loop — and how easily we misuse them without realizing.
I even added analogies (like race cars 🏎️, delivery partners 🚚, and job offers 💼) to make each concept click instantly.

If you’ve ever asked yourself “Which Promise should I use here?”, this breakdown might be worth a read.
(And yeah — it’s written for everyone from juniors to seasoned devs.)

👉 Promise.all vs allSettled vs race vs any — What Every JavaScript Developer Should Know

Curious to know:
Which one do you use most in your day-to-day code — and have you ever had a bug caused by the wrong choice?


r/JavaScriptTips • • May 14 '25

How much does it take to become Junior JS?

5 Upvotes

How much does it take for a beginner (I know CSS and HTML from 1-10, I’d say 7.5). So how much so you think it would take me to become Junior JS Developer?

Thanks in advance.