DEV Community 👩‍💻👨‍💻

Cover image for JavaScript replace a powerful tool to manipulate string
khalid ansari
khalid ansari

Posted on

JavaScript replace a powerful tool to manipulate string

Javascript replace is the most powerful tool to manipulate string and regex at its core makes it really powerful. We will deep dive into examples from basic to advance.

Replace all the occurrence of space with an underscore, a simplest use case.

const str = 'remove all the space with underscore'
str.replace(/ /g, '_')

// remove_all_the_space_with_underscore
Enter fullscreen mode Exit fullscreen mode

Replace all the number from 0 to 5 with @

const str = 'replace 1 3 5 9 all 0 to 5 number with @'
str.replace(/[0-5]/g, '@')

// replace @ @ @ 9 all @ to @ number with @
Enter fullscreen mode Exit fullscreen mode

Replace all the numbers between 0 to 5 with its square.

const str = 'replace 1 3 5 7 all 0 to 5 number with its square'

str.replace(/([0-5])/g, (match, id) => {
 return id*id 
})

// replace 1 9 25 9 7 all 0 to 25 number with its square
Enter fullscreen mode Exit fullscreen mode

You can write your own replacer function and return manipulated data. Even manipulate date inside string or deal with emoji.

  Some fun

const str = 'cry replace with smile'
str.replace(/ /g, ' ')

// 'cry replace with smile'
Enter fullscreen mode Exit fullscreen mode

Thank you for reading.

Top comments (0)

🤯

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs