Home > Mobile >  Split a sentence on question(?) mark and dot(.) and count the total words? Node js
Split a sentence on question(?) mark and dot(.) and count the total words? Node js

Time:10-04

In NodeJs how to split the sentence on question(?) mark and dot(.) and count the total words?

e.g sentence = "i am a boy. who are you?"

expected result in 3 sentence 
1.  i am a boy
2.  who are you
3. ''


1 sentence has 4 words
2 sentence has 3 words
3 sentence empty

CodePudding user response:

const string = "i am a boy. who are you?";
const sentences = string.split(/[\.\?] /);

const counts = sentences.map((str, index) => {
  const count = str ? str.trim().split(' ').length : 0;
  const returnVal = count ? `${index 1} sentence has ${count} words` : `${index 1} sentence empty`;
  return returnVal;
});

console.log(counts);

CodePudding user response:

You can pass a regex into JavaScript's split() method. For example:

let sentence = "i am a boy. who are you?";

let splitStr = sentence.split(/\?|\./)

console.log(splitStr);

console.log(splitStr.map((subStr, i)=>{
    if(subStr === '') return `${i 1} sentence empty`;
    let len = subStr.split(' ').length;
    if(len > 0) return `${i 1} sentence has ${len} words`;
    return 
}));

CodePudding user response:

let text = "i am a boy. who are you?";

let parsedText = text.split(/[\.|\?] /)
  .map(sen => sen.trim())
  .map(sen => ({
    sentence: sen,
    words: sen.split(' '),
    wordsCount: sen.split(' ').length
  }));

parsedText.forEach((s, i) => console.log(`${i 1}. ${s.sentence.length? s.sentence : "''"}`))

parsedText.forEach((s, i) => s.sentence.length ? console.log(`${i 1} sentence has ${s.wordsCount} words`) :
  console.log(`${i 1} sentence empty`)

)

  • Related