Skip to content

Instantly share code, notes, and snippets.

@peter-schmalfeldt
Created October 26, 2023 04:07
Show Gist options
  • Save peter-schmalfeldt/4c38b94cfc588b16535f6061acc0f37d to your computer and use it in GitHub Desktop.
Save peter-schmalfeldt/4c38b94cfc588b16535f6061acc0f37d to your computer and use it in GitHub Desktop.
Convert String to Emoji for SFCC XML Site Imports
/**
* Convert String to Emoji
* Most emoji's start with �
* If you have these in your SFCC Site Import XML File, you might get an import error.
*
* @usage convertStringToEmoji('��') => 🙂
* @param {String} str Raw URL Encoded String
*/
function convertStringToEmoji(str) {
// Regex matching either a surrogate or a character.
var re = /&#(\d+);|([^&])/g;
var match;
var charCodes = [];
// Find successive matches
while (match = re.exec(str)) {
if (match[1] != null) {
// Surrogate
charCodes.push(match[1]);
}
else {
// Unescaped character (assuming the code point is below 0x10000),
charCodes.push(match[2].charCodeAt(0));
}
}
// Create string from UTF-16 code units.
return String.fromCharCode.apply(null, charCodes);
}
@peter-schmalfeldt
Copy link
Author

peter-schmalfeldt commented Oct 26, 2023

Usage Instructions

For my use case, if I am doing a Site Import that has a validation error, I do the following:

  1. Download and unzip the ZIP file
  2. Open the XML file in a text editor ( on macOS TextEdit works well to open and search large files )
  3. Search for � to see if that exists in the XML, if it does, that's an emoji
  4. The emoji will be two encoded characters next to each other, e.g. ��
  5. Copy both encoded characters, e.g. �� to do a find and replace
  6. To get the converted emoji, I usually open Google Chrome and just paste that function into the Dev Console
  7. Once you have the function in a browser, you can call it, e.g. convertStringToEmoji('��')
  8. Take the emoji it output and use that as a replacement in your search
  9. Repeat steps 3-8 until you do not have any more results for �
  10. Once you are done, rezip the folder you unzipped and upload the file to be imported

This seems to fix all the issues with my imports. There are usually only a dozen or so, and most are the same, so it goes pretty quickly.


If you are using a browser, here is a clean function you can just paste in your Dev Console and press ENTER

function convertStringToEmoji(str) {
    var re = /&#(\d+);|([^&])/g;
    var match;
    var charCodes = [];
    while (match = re.exec(str)) {
      if (match[1] != null) {
        charCodes.push(match[1]);
      }
      else {
        charCodes.push(match[2].charCodeAt(0));
      }
    }
    return String.fromCharCode.apply(null, charCodes);
}

ℹ️ TIP: In Google Chrome, you can use their native copy function to copy the output of a function to your clipboard, so you can do something like this:

copy(convertStringToEmoji('��'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment