|
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 |