From 11b96d3c802e9e50fa73bf0c46e264b7bcc3b25f Mon Sep 17 00:00:00 2001 From: bholmesdev Date: Thu, 11 Aug 2022 19:18:24 -0400 Subject: [PATCH] feat: add toValidIdentifierName util --- .../mdx/lib/util/to-valid-identifier-name.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 packages/mdx/lib/util/to-valid-identifier-name.js diff --git a/packages/mdx/lib/util/to-valid-identifier-name.js b/packages/mdx/lib/util/to-valid-identifier-name.js new file mode 100644 index 000000000..25d70336c --- /dev/null +++ b/packages/mdx/lib/util/to-valid-identifier-name.js @@ -0,0 +1,16 @@ +import {start, cont} from 'estree-util-is-identifier-name' + +/** + * Replace all invalid identifier characters with underscores "_" + * @param {string} str + */ +export function toValidIdentifierName(string_) { + if (string_.length === 0) return '_' + let validString = '' + validString += start(string_[0].charCodeAt(0)) ? string_[0] : '_' + for (const char of string_.slice(1)) { + validString += cont(char.charCodeAt(0)) ? char : '_' + } + + return validString +}