One of the problems in the chapter on Strings and Regular Expressions in Modern JavaScript for the Impatient is
Write a function that, given a string, produces an escaped string delimited by ’ characters. Turn all non-ASCII Unicode into \u{. . .}. Produce escapes \b, \f, \n, \r, \t, \v, ', \.
This was a pretty interesting thing to try. Working with Unicode in Regular Expressions is a little weird and it took me a while to figure out what would match non-ASCII Unicode and replace it with a encoding.
Here is what I came up with:
function escape(str) {
str = str.replace(/\b/g, '\\b')
.replace(/\f/g, '\\f')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\v/g, '\\v')
.replace(/\'/g, "\\'")
.replace(/\\/g, '\\')
.replace(/\p{S}/gu, (match) => {
return '\\u{' +
match.codePointAt(0).toString(16) +
'}';
});
const quote = "'";
return quote + str + quote;
}
There might be a more JavaScripty way to do it, but this seems to work. It’s not very elegant, but maybe I can improve it as I practice some more.