The Most Hidden Feature of JavaScript โœ๏ธ

The Most Hidden Feature of JavaScript โœ๏ธ

ยท

2 min read

Think you know JavaScript? Think again. ๐Ÿค”

Let me tell you something about a string's replace() method... you can pass a function into it.

What does this mean? I'll show you.

Video Tutorial

If you want to see my video tutorial on this feature, feel free to watch it below ๐Ÿ‘‡

Passing a Function into the replace() method

Most of you know how the replace() method works: you pass in a string or regular expression to find alongside a replacement value.

For example, let's replace all numbers with the phrase "NUMBER":

const myString = "Order Number: 4 2 8 3";
const result = myString.replace(/\d/g, "NUMBER");

// result == "Order Number: NUMBER NUMBER NUMER NUMBER"

Pretty simple. But here's where it gets interesting ๐Ÿ‘‡

You can also pass in a function as the replacement value. The return value of that function is what gets used as the actual "replacement".

Let's see the same example as above, this time with a function instead:

const myString = "Order Number: 4 2 8 3";
const result = myString.replace(/\d/g, match => {
    return "NUMBER";
});

// result == "Order Number: NUMBER NUMBER NUMER NUMBER"

This produces the same result. But why would you want to use this technique? Well, you can add some logic ๐Ÿ˜Ž

Now, let's only replace numbers greater than 3 with the phrase "NUMBER":

const myString = "Order Number: 4 2 8 3";
const result = myString.replace(/\d/g, match => {
    if (Number(match) > 3) {
        return "NUMBER";
    }

    return match;
});

// result == "Order Number: NUMBER 2 NUMER 3"

As you may have noticed, the first argument to the replacement function is the match, which refers to each match (in our case, number) found using the first argument to the replace() method.

I hope this technique can reduce some complexity in your regular expressions ๐Ÿ˜‰

Enjoy!

Enrol Now ๐Ÿ‘‰ JavaScript DOM Crash Course

If you're learning web development, you can find a complete course on the JavaScript DOM at the link below ๐Ÿ‘‡ https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Course Thumbnail

ย