2

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

1

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.