Installation
1. Install the latest version with yarn:
yarn add string-unfancy
or with npm:
npm install string-unfancy
2. Import it in your code:
Quick Take
import { strict as assert } from "assert";
import { unfancy } from "string-unfancy";
// U+2019
// https://www.fileformat.info/info/unicode/char/2019/index.htm
// https://mothereff.in/js-escapes
const rightSingleQuote = "\u2019";
assert.equal(unfancy(`someone${rightSingleQuote}s`), "someone's");
// works with encoded HTML:
assert.equal(unfancy("someone’s"), "someone's");
Idea
Convert typographically-correct characters (like curly quotes or m-dashes) to their basic counterparts (like apostrophes or hyphens).
It’s the opposite of detergent
and string-apostrophes
.
It’s used in ASCII-restricted places where encoding is too unwieldy, for example, image alt
attribute values in email templates. Or stripping down the formatted markdown value, removing backticks and so on.
API — unfancy()
The main function unfancy()
is imported like this:
import { unfancy } from "string-unfancy";
It’s a function which takes one string input argument:
function unfancy (str: string): string;
Function will return a string.
API — version
You can import version
:
import { version } from "string-unfancy";
console.log(version);
// => "6.0.3"
Example — Gulp streams
If you are using Gulp to build email templates, you can tap
the stream, apply a function to it, then within that function, replace all instances of alt="..."
with their unfancied versions.
First, you need to require
gulp-tap and string-unfancy:
import tap from "gulp-tap";
import { unfancy } from "string-unfancy";
Then, tap your main build task’s stream, probably towards the end of the pipeline:
.pipe(tap((file) => {
file.contents = Buffer.from(unfancy(file.contents.toString()))
}))
.pipe(gulp.dest('dist')) // that's the final write happening, yours might be different
Then, declare a function somewhere within your gulpfile.js
:
function unfancy(input) {
input = input.replace(/alt="[^"]*"/g, (el) => {
return unfancy(el);
});
return input;
}
As you see above, we’re running an inline function upon all regex-matched characters.
And that’s it! All image alt
attributes will lose their HTML encoding and will have their fancy special characters converted to simple ASCII letter equivalents.
Can we use lodash.deburr
instead?
No. It won’t even convert a single m-dash! It’s a different tool for a different purpose.