From 5f0c37f98b83d8fb0e4d062631c62984e42b8ea1 Mon Sep 17 00:00:00 2001 From: Xinyi Feng Date: Mon, 22 Jul 2024 21:55:26 -0700 Subject: [PATCH] fix:remove leading hypnes when reading page metadata from Audiences,campaigns --- src/index.js | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index fd05a32..407798a 100644 --- a/src/index.js +++ b/src/index.js @@ -77,6 +77,16 @@ export function toCamelCase(name) { return toClassName(name).replace(/-([a-z])/g, (g) => g[1].toUpperCase()); } +/** + * Removes all leading hyphens from a string. + * @param {String} after the string to remove the leading hyphens from, usually is colon + * @returns {String} The string without leading hyphens + */ +export function removeLeadingHyphens(inputString) { + // Remove all leading hyphens which are converted from the space in metadata + return inputString.replace(/^(-+)/, ''); +} + /** * Retrieves the content of metadata tags. * @param {String} name The metadata name (or property) @@ -94,12 +104,13 @@ export function getMetadata(name) { */ export function getAllMetadata(scope) { const value = getMetadata(scope); - const metaTags = document.head.querySelectorAll(`meta[name^="${scope}-"], meta[property^="${scope}:-"]`); - + const metaTags = document.head.querySelectorAll(`meta[name^="${scope}"], meta[property^="${scope}:"]`); return [...metaTags].reduce((res, meta) => { - const key = meta.getAttribute('name') - ? meta.getAttribute('name').substring(scope.length + 1) - : meta.getAttribute('property').substring(scope.length + 2); + const key = removeLeadingHyphens( + meta.getAttribute('name') + ? meta.getAttribute('name').substring(scope.length) + : meta.getAttribute('property').substring(scope.length + 1), + ); const camelCaseKey = toCamelCase(key); res[camelCaseKey] = meta.getAttribute('content');