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
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 @
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
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'
Thank you for reading.
Latest comments (0)