DEV Community

Savchenkov Dmitry
Savchenkov Dmitry

Posted on

String.replace() like a pro

String.replace is a great tool to use for string formatting.
But, not any task can be solved with a simple substring replacement. Thankfully, replace method provides us with some more advanced functionality.

Replacement patterns

Let's write a function that accepts an array of 10 integers (between 0 and 9), and returns a string of those numbers in the form of a phone number.

const formatPhone = phoneInput => {
  return phoneInput
    .join('') // converting array into a string 
    .replace(/(\d{3})(\d{3})(\d+)/, '+1 ($1) $2-$3')
}

formatPhone([2,0,2,5,5,5,0,1,3,1]) // +1 (202) 555-0131
Enter fullscreen mode Exit fullscreen mode

Here we declared 3 groups in our RegExp and then pass them according to their order number to a new substring.

You can easily use named groups as well. For example, let's create a function that formats day-month-year date input to year/month/day string.

Yes, I know that there are better ways to format a date string, but it's a great example of using named replacement patterns.

const formatDate = dateInput => {
  return dateInput.replace(
    /(?<day>\d{2}).?(?<month>\d{2}).?(?<year>\d{4})/,
    '$<year>/$<month>/$<day>'
  )
}

formatDate('26-01-2022') // 2022/01/26
Enter fullscreen mode Exit fullscreen mode

If you have never used named capturing groups in RegExp you can check MDN documentation.

Passing function as a parameter

I personally think that this approach is more obvious and what more important it's easier to test and maintain.

We can pass a function that accepts each substring and returns its modified version.

As an example, we create a function that converts cameCase to a snake_case.

const camelCaseReplacer = pattern => {
  return `_${pattern.toLowerCase()}`
}

const camelCase = 'someVariableName'
camelCase.replace(/[A-Z]/g, camelCaseReplacer) // some_variable_name
Enter fullscreen mode Exit fullscreen mode

These techniques will help you to solve almost any string formatting challenges, so don't hesitate to use them.

Top comments (0)