You can replace strings.

const string = 'hello dude'
string.replace('e', '*')
// h*llo dude'

You can replace multiple strings with RegExp.

const string = 'hello dude'
string.replace(/e/g, '*')
// 'h*llo dud*'

You can target just the beginning of lines.

const string = 'hello dude\nhow is your hearing?'
string.replace(/^h/g, '*')
// '*ello dude\nhow is your hearing?'

kook

Wait, why didn’t that work?

You forgot the multi-line option.

const string = 'hello dude\nhow is your hearing?'
string.replace(/^h/gm, '*')
// '*ello dude\n*ow is your hearing?'

You can use capturing groups.

const string = 'hello dude\nhow is your hearing?'
string.replace(/(^h\w+)/gm, (match, hWord) => {
  return hWord.toUpperCase()
})
// 'HELLO dude\nHOW is your hearing?'

Optional capturing groups are included in the results, as undefined.

const string = 'hello dude\nhow is your hearing?\nDid you see my horse?'
const regex = /(^h\w+)?(.+?)(\?)?$/gm
string.replace(regex, (match, hWord, otherStuff, questionMark) => {
  console.log({ hWord, otherStuff, questionMark })
  return match
})
// { hWord: 'hello', otherStuff: ' dude', questionMark: undefined }
// { hWord: 'how', otherStuff: ' is your hearing', questionMark: '?' }
// { hWord: undefined, otherStuff: 'Did you see my horse', questionMark: '?' }

Note the cool trick to help your console.log debugging process. ;)


Refs