const regex = /(?: # Non capturing group 1
\G # Matches where the regex engine stops in the previous step
(\w+) # capture group 1: a regex word of 1+ chars
\h* # zero or more horizontal spaces (space, tabs)
(?: # Non capturing group 2
=\h* # literal '=' follower by zero or more hspaces
(\w+) # capture group 2: a regex word of 1+ chars
)? # make the non capturing group 2 optional
)+ # repeat the non capturing group 1, one or more/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?: # Non capturing group 1
\\G # Matches where the regex engine stops in the previous step
(\\w+) # capture group 1: a regex word of 1+ chars
\\h* # zero or more horizontal spaces (space, tabs)
(?: # Non capturing group 2
=\\h* # literal \'=\' follower by zero or more hspaces
(\\w+) # capture group 2: a regex word of 1+ chars
)? # make the non capturing group 2 optional
)+ # repeat the non capturing group 1, one or more', 'g')
const str = `Key name = value`;
const subst = `\1\2`;
// 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