Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Created May 13, 2016 03:47
Show Gist options
  • Save nuxlli/33af5b8b7aec7de6e50abb52cf3fa3f4 to your computer and use it in GitHub Desktop.
Save nuxlli/33af5b8b7aec7de6e50abb52cf3fa3f4 to your computer and use it in GitHub Desktop.
Replace shell envs
// https://regex101.com/r/rK1eJ0/6
var regex_envs = /(\\*)(\$(?:(?:[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)|(?:{[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)}))))/g
function replaceEnvs(str, replace_for = "$1") {
return str.replace(regex_envs, (_match, slashs, v1, v2, v3) => {
if (slashs.length == 0 || slashs.length % 2 == 0) {
var value = v2 === undefined ? v3 : v2;
return `${slashs}${replace_for.replace("$1", value)}`;
} else if (slashs.length > 0) {
return `${slashs.slice(0,slashs.length-1)}${v1}`;
} else {
return _match;
}
});
}
@fearenales
Copy link

fearenales commented May 13, 2016

// https://regex101.com/r/rK1eJ0/6
var regex_envs = /(\\*)(\$(?:(?:[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)|(?:{[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)}))))/g

function replaceEnvs(str, replace_for = "$1") {
  return str.replace(regex_envs, (_match, slashes, v1, v2, v3) => {
    if (slashes.length % 2 == 0) {
      var value = v2 || v3;
      return `${slashes}${replace_for.replace("$1", value)}`;
    } else if (slashes.length) {
      return `${slashes.slice(0, slashes.length-1)}${v1}`;
    } else {
      return _match;
    }
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment