Home > OS >  regex remove short sentences callouts
regex remove short sentences callouts

Time:03-23

I want to remove all short sentences (callouts) from a string. See my example below. I want to remove all highlighted text. Maybe text < 25 characters that end with "." enter image description here

CodePudding user response:

This regex will target sentenses with a max length of 25.

/(?<=^|\.)\s*.{1,25}?\./gms

Test snippet :

const regex = /(?<=^|\.)\s*.{1,25}?\./gms;
const str = `This is a test.  Keep this longer text that has over 25 characters.  Remove this small text.  `;

const result = str.replace(regex, '');

console.log(result);

Or without a look-behind. For the browsers that stay behind.

/(^|\.)\s*.{1,25}?\./gms

Substitute with first capture group.

const regex = /(^|\.)\s*.{1,25}?\./gms;
const str = `This is a test.  Keep this longer text that has over 25 characters.  
Remove this small text.  `;

const result = str.replace(regex, '$1');

console.log(result);

CodePudding user response:

Maybe this one helps. I didn't consider the '.' char Because I populated this sentence in JS.

const sentence = (() => {
    const sentences = [];
    for (let i = 0; i < 15; i  ) {
        const len = Math.floor(Math.random() * (30 - 15   1)   15);
        const sentence = [];
        for (let j = 0; j < len; j  ) {
        sentence.push(String.fromCharCode(Math.floor(Math.random() * (122 - 97   1)   97)));
        }
        sentences.push(sentence.join(''));
    }
    return sentences
    })();

    console.log(sentence.length)
    console.log(sentence)
    console.log(sentence.filter(s => s.length > 24))
    console.log(sentence.filter(s => s.length > 24).length)

  • Related