Home > Mobile >  Match and replace regex with modified regex in JS
Match and replace regex with modified regex in JS

Time:09-10

Currently I'm going through a string like so:

'@test1 in else',
'@test2 in something',

and look only for

test1
test2

my goal is to have end result of string to look like this:

'([@test1])(test1) in else',
'((@test2))(test2) in something',

This is what I do but clearly it doesn't work:

fileData.replace(/@(\w) /g, '(['   /@(\w) /g   ']('   /@(\w) /g)   ')')

I don't understand how can I save the regex that I found and use it in modified version

CodePudding user response:

You can use this code:

const str = `'@test1 in else',
'@test2 in something',`;
var repl = str.replace(/@(\w )/g, '([@$1])($1)');

console.log(repl);

RegEx Demo

Breakup:

  • @(\w ): Match a text starting with @ followed by 1 word charts and capture word chars in capture group #1
  • ([@$1])($1): Replacement part to place capture text in wrapper brackets twice
  • Related