index.js 1.03 KB
/**
 * 将文本中的 {{ code }} 替换为数组中对应 item 的 {{ name }}
 * @param {string} text - 包含 {{ code }} 占位符的文本
 * @param {Array<{code: string, name: string}>} arr - 映射数组
 * @returns {string} 替换后的文本
 */
export function replaceCodeWithName(text, arr) {
	return text.replace(/\{\{\s*(\S+?)\s*\}\}/g, (match, code) => {
		const item = arr.find(item => item.code === code);
		return item ? `{{ ${item.name} }}` : match;
	});
}

/**
 * 将文本中的 {{ name }} 替换为数组中对应 item 的 {{ code }}
 * @param {string} text - 包含 {{ name }} 占位符的文本
 * @param {Array<{code: string, name: string}>} arr - 映射数组
 * @returns {string} 替换后的文本
 */
export function replaceNameWithCode(text, arr) {
	let result = text;
	arr.forEach((item) => {
		result = result.replace(
			new RegExp(`\\{\\{\\s*${escapeRegExp(item.name)}\\s*\\}\\}`, "g"),
			`{{ ${item.code} }}`,
		);
	});
	return result;
}

function escapeRegExp(str) {
	return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}