DEV Community

Cover image for The Most Hidden Feature of JavaScript ✍️
Dom (dcode)
Dom (dcode)

Posted on

The Most Hidden Feature of JavaScript ✍️

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)