Mike K
Mike K

Reputation: 6491

How to prefix certain characters in a string with regex?

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?

Upvotes: 1

Views: 98

Answers (1)

depperm
depperm

Reputation: 10746

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)

Upvotes: 2

Related Questions