const regex = /([^_\n]*)_([^_\n]*)(_.*)?|(.*)(?<!-)-(?!-)(\w+)(.*)/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('([^_\\n]*)_([^_\\n]*)(_.*)?|(.*)(?<!-)-(?!-)(\\w+)(.*)', 'g')
const str = `foo_bar_something-like_this-me
bar--foo_something-like_this-me--
something-like--bar--foo_this-me----
this-me------something-like--bar--foo--
--this-me------something--bar--foo----like
----this------something--bar--foo----like--me
`;
const subst = `$2--$1$3$4$6--$5`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions