@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
43 lines • 1.98 kB
JavaScript
/**
* 2025-01-17: Migrated from SP-API-Tester
* The purpose of this function is to
* 1. Take a rich text field from a list item
* 2. Strip any Div tags from the string
* if onlyStripOutterTags === true, then it only strips the outter HTML tags from the RichText field
* if you set this to false, it may also strip any inner tags from things like analytics with rich text tags in the json
* onlyStripOutterTags has only been tested in it's default state for SP-API-Tester
* For example... zzzRichText1: '<div class="ExternalClassA265D727B17142199E957A374E3FD155">{html: "<span>Hello</span>" }'
* onlyStripOutterTags === true should return: {html: "<span>Hello</span>" }
* onlyStripOutterTags !== true should return: {html: "Hello" }
* 3. Decode any Html Entities
* 4. Try to convert the remaining string into a JSON object
*
* @param richTextValue
* @param onlyStripOutterTags
* @returns
*/
export function parseRichTextFieldAsJsonObject(richTextValue, onlyStripOutterTags = true) {
// Step 1: Strip HTML tags
if (!richTextValue)
return null;
const strippedValue = onlyStripOutterTags === true ? richTextValue.replace(/^<[^>]+>|<[^>]+>$/g, '') : richTextValue.replace(/<\/?[^>]+(>|$)/g, '');
// Step 2: Decode HTML entities
const decodedValue = decodeHtmlEntities(strippedValue);
// Step 3: Parse JSON
try {
const jsonObject = JSON.parse(decodedValue);
return jsonObject;
}
catch (error) {
console.error('Failed to parse JSON:', error);
return null;
}
}
function decodeHtmlEntities(htmlString) {
// Create a temporary DOM element to decode HTML entities
const textarea = document.createElement('textarea');
textarea.innerHTML = htmlString;
const value = `${textarea.value}`;
return value;
}
//# sourceMappingURL=parseRichTextFieldAsJsonObject.js.map