oreoman
oreoman

Reputation: 21

replace string into bracket in javascript regex

im trying this

str = "@a@b";
str2 = str.replace(/@/g,'-[' + str + ']');

output should be -[a]-[b]

Upvotes: 0

Views: 58

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

You could search for @ and not @ as following, then replace the group.

/@([^@]+)/g
 @           look for this character literately
  (     )    group, this is the part used for replacing -> $1 in replacement string
   [^@]+     look for one or more not @ characters
          g  global flag, replace all found matches

The replacement is made with the first group $1.

var str = "@a@b",
    str2 = str.replace(/@([^@]+)/g,'-[$1]');

console.log(str2);

Upvotes: 6

The fourth bird
The fourth bird

Reputation: 163277

You could do it like this and replace with group 1 -[$1]

var str = "@a@b";
var str2 = str.replace(/@(.)/g, '-[$1]');
console.log(str2);

@(.)

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

You can use replacer function

var str = "@a@b";
console.log( str.replace(/@\w/g, m => "[" + m.substring(1) + "]") );

Upvotes: 0

Related Questions