replace.js 740 B

1234567891011121314151617181920212223242526
  1. import { get } from "lodash";
  2. /**
  3. * 必须是合法的标识符
  4. */
  5. export const PLACEHOLDER_REGEXP = /\{\s*(['"a-zA-Z0-9_$.[\]]+)\s*\}/gm;
  6. export function variableReplace(variables, local) {
  7. Object.keys(variables).forEach((key) => {
  8. const value = variables[key];
  9. if (typeof value === "string") {
  10. const replaced = stringReplace(value, local);
  11. if (replaced !== value) {
  12. variables[key] = replaced;
  13. }
  14. }
  15. });
  16. return variables;
  17. }
  18. export function stringReplace(source, local) {
  19. // 快捷判断
  20. if (!source.includes("{")) {
  21. return source;
  22. }
  23. return source.replace(PLACEHOLDER_REGEXP, (m, p) => {
  24. return get(local, p);
  25. });
  26. }