Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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/)'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/)'

>Solution :

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\)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading