2

I want to find all @mention occurrences in a comment and replace them with a different format.

I have this regex that groups all occurrences, but all this point I would have to manipulate these strings for Jira ([~string]), and plug them back into the original string.

comment.match(/[ ]@[^\s]+/g);

Is there a better way?

Comment entered:

guiyjhk @test hgjhgjh test@this_is.test2 jhgjhgjh @this_is.test2

This is what I want to be returned:

guiyjhk [~test] hgjhgjh test@this_is.test2 jhgjhgjh [~this_is.test2]
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
bonum_cete
  • 4,730
  • 6
  • 32
  • 56
  • Possible duplicate of [JavaScript replace/regex](https://stackoverflow.com/questions/1162529/javascript-replace-regex) – Abion47 Aug 08 '18 at 17:33

2 Answers2

4

You can match with a regex the captures the part after the @ and the spaces before and use replace() to replace those matches. This will allow you to match @mention surrounded by whitespace while avoiding test@this_is.test2

let comment = "guiyjhk @test hgjhgjh test@this_is.test2 jhgjhgjh @this_is.test2"

// catch space then @ then non-space replace with space(s)[non-space]
comment = comment.replace(/([\s+])@([^\s]+)/g, "$1[~$2]");
console.log(comment)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You could capture zero or more times a whitespace or assert the start of the string in group 1 , match an @ followed by capturing in a group not a whitespace \S+

(^|\s+)@(\S+)

Then in the replacement use group 1 and 2 $1[~$2]

const strings = [
  "guiyjhk @test hgjhgjh test@this_is.test2 jhgjhgjh @this_is.test2",
  "@test"
];
strings.forEach((s) => {
  console.log(s.replace(/@(\S+)/g, "[~$1]"));
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70