JSFiddle - React, Tailwind, and code Playground
by Abdul Ahmad
JavaScript
class TextBuilder {
finalString = '';
wordsToCaps = [];
constructor({ wordsToCaps = [] } = {}) {
this.wordsToCaps = wordsToCaps;
}
addText({
text = '',
startPunctuation,
endPunctuation,
capitalizeAfterPunctuation = true,
capitalizeFirstLetter = true,
addSpaceBeforeNewText = true,
wordsToCaps = [],
persistWordsToCaps = false,
} = {}) {
text = text.trim();
text = this._capitalizeAllWordsToCaps({ wordsToCaps, text, persistWordsToCaps });
if (!this.finalString.trim()) text = this._capitalizeLetter({ text });
if (this._lastCharIsPunctuation({ text: this.finalString })) {
if (
capitalizeFirstLetter
&& this._lastCharIsPunctuation({ text: this.finalString, requiresCaps: true })
) text = this._capitalizeLetter({ text });
this.finalString += ' ';
}
if (startPunctuation) {
this.finalString += startPunctuation + ' ';
if (capitalizeAfterPunctuation) text = this._capitalizeLetter({ text });
}
if (
addSpaceBeforeNewText
&& this._lastCharIsLetter({ text: this.finalString })
&& this._firstCharIsLetter({ text })
) text = ' ' + text;
if (this._firstCharIsPunctuation({ text, requiresCaps: true })) {
text = this._capitalizeLetter({ text, first: false });
}
this.finalString += text;
if (endPunctuation) this.finalString += endPunctuation;
}
printText() {
console.log('Text: ', this.finalString)
}
_capitalizeAllWordsToCaps({ wordsToCaps = [], text = '', persistWordsToCaps }) {
const allWordsToCaps = [ ...this.wordsToCaps, ...wordsToCaps ];
if (
persistWordsToCaps
&& wordsToCaps
&& wordsToCaps.length
) this.wordsToCaps = [...this.wordsToCaps, ...wordsToCaps];
if (!allWordsToCaps || !allWordsToCaps.length) return text;
allWordsToCaps.forEach(wordToCaps => {
const capitalized = this._capitalizeLetter({ text: wordToCaps });
text =...