I want to write a script that checks the number of characters (excluding whitespace) in a sentence. For example: "this is a sentence" would be 15 characters. If the sentence contains a break like '.' it should be counted as a different sentence.
I have started writing the script but I think I need some help.
function(sen) {
return sen.split('.').forEach(function(part) { part.match(/\s*/).result })
}
Split by a period and use map to extract the length property:
function check(sen) {
return sen.split('.').map(e => e.length)
}
console.log(check("Hello. World"))
If you only want the length of the first sentence, split by a period, get the first item and return its length property:
function check(sen) {
return sen.split('.')[0].length;
}
console.log(check("Hello. World"))
const str = 'this is first sentence. this is second sentence';
let sentence = str.split('.');
let result = {};
sentence.forEach((value, index) => {
result[index + 1] = value.length;
});
console.log(result);
The output will contain character length with respect to the sentence number.
(Discounting emojis) Use a regex replace on the whitespaces so you clear them out first..
sen.replace(/\s*/g, '')
and then split the sentence and count the number of characters
function sentenceCounter(sen) {
return sen.replace(/\s*/g, '').split('.').map(e => e.length)
}
Thats all you should need really, this should return a list of numbers corresponding to the length of your sentences