Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:44
Show Gist options
  • Save rfprod/02feb29817c6f710f0f4f5d9fbeb26a2 to your computer and use it in GitHub Desktop.
Save rfprod/02feb29817c6f710f0f4f5d9fbeb26a2 to your computer and use it in GitHub Desktop.
Speech Fixer and Censor
function fixAndCensor(input,ok) {
ok = (ok) ? ok : [];
ok.forEach((item, index) => ok[index] = item.toLowerCase());
//console.log('ok', ok);
let output = '';
while (input !== '') {
//console.log(output);
const matches = new RegExp(/[^\s]+(?=(\s|\W){1})/).exec(input);
//console.log('matches:', matches);
//console.log('input:', input);
let asterisks = '';
if (matches) {
if (matches[0].length > 2 && ok.indexOf(matches[0].replace(/\W/g, '').toLowerCase()) === -1) {
for (let i = 0, max = matches[0].length - 2; i < max; i++) { asterisks += '*'; }
if (matches[0][matches[0].length - 1].match(/(\.|\!|\?|,|\:|;)/)) {
matches[0] = matches[0][0] + asterisks.slice(1) + matches[0].substring(matches[0].length - 2, matches[0].length);
} else {
matches[0] = matches[0][0] + asterisks + matches[0][matches[0].length - 1];
}
}
if (output.length === 0) {
output += matches[0][0].toUpperCase() + matches[0].slice(1).toLowerCase() + matches[1].toLowerCase();
} else {
//console.log('previous char:', output[output.length - 2]);
if (output[output.length - 2].match(/(\.|\!|\?)/)) {
output += matches[0][0].toUpperCase() + matches[0].slice(1).toLowerCase() + matches[1].toLowerCase();
} else {
output += matches[0].toLowerCase() + matches[1].toLowerCase();
}
}
input = input.slice(matches[0].length + matches[1].length);
} else {
//console.log('ends without any punctuation');
if (input.length > 2 && ok.indexOf(input.replace(/\W/g, '').toLowerCase()) === -1) {
let asterisks = '';
for (let i = 0, max = input.length - 2; i < max; i++) { asterisks += '*'; }
input = input[0] + asterisks + input[input.length - 1];
}
if (output[output.length - 2].match(/(\.|\!|\?)/)) {
output += input[0].toUpperCase() + input.slice(1).toLowerCase();
} else {
output += input.toLowerCase();
}
input = '';
}
//console.log('output:', output);
}
return output;
}
fixAndCensor("This is a saple sentence, test",["sample","test"]); // T**s is a sampe s******e, test

Speech fixer and censor

Fixes case for letters according to punctuation and word positioning in the sentence. Censores all words longer that 2 characters by replacing all letters with asterisks except the fitst and the last by default. Function can be passed and array of allowed words, these will not be censored with asterisks.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment