Reputation: 21
im trying this
str = "@a@b";
str2 = str.replace(/@/g,'-[' + str + ']');
output should be -[a]-[b]
Upvotes: 0
Views: 58
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
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
Reputation: 68393
You can use replacer function
var str = "@a@b";
console.log( str.replace(/@\w/g, m => "[" + m.substring(1) + "]") );
Upvotes: 0