Member-only story

N Powerful and Useful Regular Expressions

Beck Moulton
4 min readJul 31, 2023

--

Regular Expression is a powerful string pattern matching tool. Mastering common Regular Expression can greatly improve our efficiency in string manipulation and text processing.

1. Currency formatting

I often need to use formatted currency in my work, and using Regular Expression makes it very easy.

const formatPrice = (price) => {
const regexp = new RegExp(`(?!^)(?=(\d{3})+${price.includes('.') ? '\.' : '$'})`, 'g')
return price.replace(regexp, ',')
}

formatPrice('123') // 123
formatPrice('1234') // 1,234
formatPrice('123456') // 123,456
formatPrice('123456789') // 123,456,789
formatPrice('123456789.123') // 123,456,789.123

Do you have any other methods? Using Intl. NumberFormat is my favorite way.

const format = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
})

console.log(format.format(123456789.123)) // $123,456,789.12

There is more than one way to fix it! I have another way to make me happy.

const amount = 1234567.89
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

console.log(formatter.format(amount)) // $1,234,567.89

Why should I learn Regular Expression? It looks so complicated! I lost confidence.

Take it easy, my friend, and you will see the magic of Regular Expression.

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet