Home > Back-end >  Replace and transform text using regex
Replace and transform text using regex

Time:11-03

I have a text with a pattern. And it needs to be transformed to a text that is more readable to the user.

//Rawtext => transformed text
@[John](john@gmail.com), how are you? => @John, how are you?
Good morning @[Doe](doe@gmail.com) => Good morning @Doe.

Any help is deeply appreciated. Thanks in advance.

Note: related to the react-mentions package for reactjs

CodePudding user response:

This might work.

const regex = /@\[([^\]] )\]\([^\)] \)/g;

console.log('@[John]([email protected]), how are you?'.replace(regex, '@$1'));
console.log('Good morning @[Doe]([email protected])'.replace(regex, '@$1'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Here is one way to do it:

const re = /\[(\w )\]|\(. \)/g

const a = '@[John]([email protected]), how are you?'
const b = 'Good morning @[Doe]([email protected])'

const result_A = a.replace(re, '$1')
const result_B = b.replace(re, '$1')

console.log(result_A)
console.log(result_B)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related