Home > Net >  How can I add a symbol in front of specified symbols?
How can I add a symbol in front of specified symbols?

Time:10-12

I am having a string which includes also symbols like '( ) |' and maybe more in future.

I would like to add another symbol, in front of them.

String: 'Hi, my name | nick is Dave (for friends)' Expectation : 'Hi, my name /| nick is Dave /(for friends/)'

So far I have tried replace() (replace only first one, failed), replaceAll() (didnt even work at all).

Right now I have this working code, but its too long, I would love to have one regex, where I specify all symbols, where I want to insert the symbol '/' in front of.

Or any other solution to shorten the code, and make it more simple.

My working code, I would like to improve:

const string= 'Hi, my name | nick is Dave (for friends)'
   const firstString = string.split('|').join("/|")
   const secondString = firstString.split('(').join("/(")
   const thirdString = secondString.split(')').join("/)")

Result is thirdString = 'Hi, my name /| nick is Dave /(for friends/)'

CodePudding user response:

I suggest using .replace here instead of .split:

string.replace(/[|()]/g, '\\$&')

Here [|()] matches one of the given characters inside the character class and '\\$&' prepends \ before the match.

Code:

const string= 'Hi, my name | nick is Dave (for friends)';
var repl = string.replace(/[|()]/g, '\\$&');

console.log(repl);
//=> Hi, my name \| nick is Dave \(for friends\)

  • Related