string.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import {isArray} from "@/utils/validate";
  2. /**
  3. * 根据模板生成字符串
  4. * @param data 数据
  5. * @param template 模板
  6. * @returns 字符串
  7. */
  8. export function formatStringByTemplate(data: any, template: string) {
  9. let result = template
  10. if (data) {
  11. if (isArray(data)) {
  12. if (data.length === 0) {
  13. return result;
  14. }
  15. // 数组
  16. return formatStringByList(data, result);
  17. } else {
  18. return replaceText(result, data);
  19. }
  20. }
  21. return result;
  22. }
  23. /**
  24. * [[{{姓名}}任{{职务}},负责{{工作职责}}]]
  25. * @param data
  26. * @param template
  27. * @returns {*}
  28. */
  29. function formatStringByList(list: any[], template: string) {
  30. let result = template
  31. const regex = /\[\[.*?\]\]/g
  32. let templates = result.match(regex)
  33. const keys = Object.keys(list[0]);
  34. const templatess: any[] = []
  35. templates?.forEach(t => {
  36. let temp = t.substring(2, t.length - 2);
  37. let temps: any[] = []
  38. list.forEach(d => temps.push(replaceText(temp, d)))
  39. let ts = temps.join(';');
  40. if (ts.length > 0 && !ts.endsWith('。')) {
  41. ts = ts + '。'
  42. }
  43. templatess.push(ts)
  44. })
  45. templates?.forEach((ts, index) => {
  46. result = result.replace(ts, templatess[index])
  47. })
  48. return result;
  49. }
  50. function replaceText2(template: string, data: { [key: string]: any }) {
  51. const keys = Object.keys(data);
  52. keys.forEach(key => {
  53. template = template.replace(new RegExp('{{' + key + '}}', 'g'), data[key] || '');
  54. });
  55. return template;
  56. }
  57. function replaceText(template: string, data: any) {
  58. // 正则表达式,用于匹配{{key}},包括可能存在的空格
  59. const regex = /{{\s*([^}]+?)\s*}}/g;
  60. // 递归函数,用于处理嵌套对象
  61. function replaceValue(key: string) {
  62. // 分割键名,以处理嵌套对象
  63. const keys = key.split('.');
  64. let value = data;
  65. for (const k of keys) {
  66. // 如果值为undefined或null,则停止查找
  67. if (value === undefined || value === null) break;
  68. value = value[k];
  69. }
  70. // 如果找到的值是undefined或null,则替换为空字符串
  71. return value === undefined || value === null ? '' : value;
  72. }
  73. // 使用正则表达式替换模板中的所有匹配项
  74. return template.replace(regex, (match, key) => replaceValue(key));
  75. }