Home > Net >  How to prefix certain characters in a string with regex?
How to prefix certain characters in a string with regex?

Time:02-03

Suppose the following,

const str = `
    hello!
    proceed - click button below.
`

I need to prefix certain characters with \\. In this case, I need the following result:

`
    hello\\!
    proceed \\- click button below\\.
`

Currently, I am doing this:

const str = `
    hello!
    proceed - click button below.
`.replace(/!/gm, '\\!').replace(/-/gm, '\\-').replace(/\./gm, '\\.')

console.log(str);

Seems messy. Any better way to do it?

CodePudding user response:

Use capture groups. Inside group () have the characters you'd like to replace [!\-.] and then in the replace reference the group $1. You also need to add extra \\ to get 2 in the final output

const str = `
    hello!
    proceed - click button below.
`.replace(/([!\-.])/gm, '\\\\$1')
console.log(str)

  • Related