UNPKG

prevent-widows

Version:

Prevent widows from appearing in a string.

51 lines (50 loc) 2.05 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const encodings_1 = __importDefault(require("./encodings")); const defaultPreventWidowsOptions = { encoding: encodings_1.default.HTML, }; const preventWidows = (text, customPreventWidowsOptions = defaultPreventWidowsOptions) => { const options = Object.assign(Object.assign({}, defaultPreventWidowsOptions), customPreventWidowsOptions); const { encoding } = options; const startAt = text.trimEnd().length - 1; let lastNbsp = -1, lastSpace = -1, lastNbHypen = -1, lastHyphen = -1; if (encoding.space) { lastNbsp = text.lastIndexOf(encoding.space, startAt); lastSpace = text.lastIndexOf(" ", startAt); } if (encoding.hyphen) { lastNbHypen = text.lastIndexOf(encoding.hyphen, startAt); lastHyphen = text.lastIndexOf("-", startAt); } // Identify which character is last const lastCharacter = Math.max(lastNbsp, lastSpace, lastNbHypen, lastHyphen); // Is the last character a Single word? Non-breaking character already? // Then no action is required if ([-1, lastNbsp, lastNbHypen].includes(lastCharacter)) { return text; } const beforeLastCharacter = text.substring(0, lastCharacter).trimEnd(); const afterLastCharacter = text.substring(lastCharacter + 1); // If there is only one word in the paragraph, do nothing if (beforeLastCharacter == "") { return text; } let conjuction = ""; // Depending on the last character in the sentence switch (lastCharacter) { // Replace space case lastSpace: conjuction = encoding.space; break; // Replace hyphens case lastHyphen: conjuction = encoding.hyphen; break; } return [beforeLastCharacter, afterLastCharacter].join(conjuction); }; exports.default = preventWidows;