MCPcopy Index your code
hub / github.com/nodejs/node / strEscape

Function strEscape

lib/internal/util/inspect.js:787–850  ·  view source on GitHub ↗
(str)

Source from the content-addressed store, hash-verified

785// Escape control characters, single quotes and the backslash.
786// This is similar to JSON stringify escaping.
787function strEscape(str) {
788 let escapeTest = strEscapeSequencesRegExp;
789 let escapeReplace = strEscapeSequencesReplacer;
790 let singleQuote = 39;
791
792 // Check for double quotes. If not present, do not escape single quotes and
793 // instead wrap the text in double quotes. If double quotes exist, check for
794 // backticks. If they do not exist, use those as fallback instead of the
795 // double quotes.
796 if (StringPrototypeIncludes(str, "'")) {
797 // This invalidates the charCode and therefore can not be matched for
798 // anymore.
799 if (!StringPrototypeIncludes(str, '"')) {
800 singleQuote = -1;
801 } else if (!StringPrototypeIncludes(str, '`') &&
802 !StringPrototypeIncludes(str, '${')) {
803 singleQuote = -2;
804 }
805 if (singleQuote !== 39) {
806 escapeTest = strEscapeSequencesRegExpSingle;
807 escapeReplace = strEscapeSequencesReplacerSingle;
808 }
809 }
810
811 // Some magic numbers that worked out fine while benchmarking with v8 6.0
812 if (str.length < 5000 && RegExpPrototypeExec(escapeTest, str) === null)
813 return addQuotes(str, singleQuote);
814 if (str.length > 100) {
815 str = RegExpPrototypeSymbolReplace(escapeReplace, str, escapeFn);
816 return addQuotes(str, singleQuote);
817 }
818
819 let result = '';
820 let last = 0;
821 for (let i = 0; i < str.length; i++) {
822 const point = StringPrototypeCharCodeAt(str, i);
823 if (point === singleQuote ||
824 point === 92 ||
825 point < 32 ||
826 (point > 126 && point < 160)) {
827 if (last === i) {
828 result += meta[point];
829 } else {
830 result += `${StringPrototypeSlice(str, last, i)}${meta[point]}`;
831 }
832 last = i + 1;
833 } else if (point >= 0xd800 && point <= 0xdfff) {
834 if (point <= 0xdbff && i + 1 < str.length) {
835 const point = StringPrototypeCharCodeAt(str, i + 1);
836 if (point >= 0xdc00 && point <= 0xdfff) {
837 i++;
838 continue;
839 }
840 }
841 result += `${StringPrototypeSlice(str, last, i)}\\u${NumberPrototypeToString(point, 16)}`;
842 last = i + 1;
843 }
844 }

Callers 2

formatPrimitiveFunction · 0.85
formatPropertyFunction · 0.85

Calls 1

addQuotesFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…