Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6628933
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T22:11:18+00:00 2026-05-25T22:11:18+00:00

I’m looking for a javascript function that is smart enough to remove the last

  • 0

I’m looking for a javascript function that is smart enough to remove the last sentence of a long chunk of text (one paragraph actually). Some example text to show the complexity:

<p>Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said. He later described it as: "Something insane."</p>

Now I could split on . and remove the last entry of the array but that would not work for sentences ending with ? or ! and some sentences end with quotes like something: "stuff."

function removeLastSentence(text) {
  sWithoutLastSentence = ...; // ??
  return sWithoutLastSentence;
}

How to do this? What’s a proper algorithm?

Edit – By long text I mean all the content in my paragraph and by sentence I mean an actual sentence (not a line), so in my example the last sentence is: He later described it as: "Something insane." When that one is removed, the next one is She did not know, "I think we should move past the fence!", she quickly said."

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T22:11:19+00:00Added an answer on May 25, 2026 at 10:11 pm

    Define your rules:
    // 1. A sentence Starts with a Capital letter
    // 2. A sentence is preceded by nothing or [.!?], but not [,:;]
    // 3. A sentence may be preceded by quotes if not formatted properly, such as [“‘]
    // 4. A sentence may be incorrectly in this case if the word following a quote is a Name

    Any additional Rules?

    Define your Purpose:
    // 1. Remove the last sentence

    Assumptions:
    If you started from the last character in the string of text and worked backwards, then you’d identify the beginning of the sentence as:
    1. The string of text before the character is [.?!] OR
    2. The string of text before the character is [“‘] and preceded by a Capital letter
    3. Every [.] is preceded by a space
    4. We aren’t correcting for html tags
    5. These assumptions are not robust and will need to be adapted regularly

    Possible Solution:
    Read in your string and split it on the space character to give us chunks of strings to review in reverse.

    var characterGroups = $('#this-paragraph').html().split(' ').reverse();
    

    If your string is:

    Blabla, some more text here. Sometimes basic html code is used but that should not make the “selection” of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: “What is it doing up there?” She did not know, “I think we should move past the fence!”, she quickly said. He later described it as: “Something insane.”

    var originalString = 'Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said. He later described it as: "Something insane."';
    

    Then your array in characterGroups would be:

        ["insane."", ""Something", "as:", "it", "described", "later", "He",
     "said.", "quickly", "she", "fence!",", "the", "past", "move", "should", "we",
     "think", ""I", "know,", "not", "did", "She", "there?"", "up", "doing", "it",
     "is", ""What", "mind:", "to", "came", "that", "thing", "first", "the", "asked",
     "I", "over.", "flying", "plane", "a", "saw", "I", "and", "window", "the", "up",
     "looked", "I", "harder!", "any", "sentence", "the", "of", ""selection"", "the",
     "make", "not", "should", "that", "but", "used", "is", "code", "html", "basic",
     "Sometimes", "here.", "text", "more", "some", "Blabla,"]
    

    Note: the ” tags and others would be removed using the .text() method in jQuery

    Each block is followed by a space, so when we have identified our sentence start position (by array index) we’ll know what index the space had and we can split the original string in the location where the space occupies that index from the end of the sentence.

    Give ourselves a variable to mark if we’ve found it or not and a variable to hold the index position of the array element we identify as holding the start of the last sentence:

    var found = false;
    var index = null;
    

    Loop through the array and look for any element ending in [.!?] OR ending in ” where the previous element started with a capital letter.

    var position     = 1,//skip the first one since we know that's the end anyway
        elements     = characterGroups.length,
        element      = null,
        prevHadUpper = false,
        last         = null;
    
    while(!found && position < elements) {
        element = characterGroups[position].split('');
    
        if(element.length > 0) {
           last = element[element.length-1];
    
           // test last character rule
           if(
              last=='.'                      // ends in '.'
              || last=='!'                   // ends in '!'
              || last=='?'                   // ends in '?'
              || (last=='"' && prevHadUpper) // ends in '"' and previous started [A-Z]
           ) {
              found = true;
              index = position-1;
              lookFor = last+' '+characterGroups[position-1];
           } else {
              if(element[0] == element[0].toUpperCase()) {
                 prevHadUpper = true;
              } else {
                 prevHadUpper = false;
              }
           }
        } else {
           prevHadUpper = false;
        }
        position++;
    }
    

    If you run the above script it will correctly identify ‘He’ as the start of the last sentence.

    console.log(characterGroups[index]); // He at index=6
    

    Now you can run through the string you had before:

    var trimPosition = originalString.lastIndexOf(lookFor)+1;
    var updatedString = originalString.substr(0,trimPosition);
    console.log(updatedString);
    
    // Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said.
    

    Run it again and get:
    Blabla, some more text here. Sometimes basic html code is used but that should not make the “selection” of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: “What is it doing up there?”

    Run it again and get:
    Blabla, some more text here. Sometimes basic html code is used but that should not make the “selection” of the sentence any harder! I looked up the window and I saw a plane flying over.

    Run it again and get:
    Blabla, some more text here. Sometimes basic html code is used but that should not make the “selection” of the sentence any harder!

    Run it again and get:
    Blabla, some more text here.

    Run it again and get:
    Blabla, some more text here.

    So, I think this matches what you’re looking for?

    As a function:

    function trimSentence(string){
        var found = false;
        var index = null;
    
        var characterGroups = string.split(' ').reverse();
    
        var position     = 1,//skip the first one since we know that's the end anyway
            elements     = characterGroups.length,
            element      = null,
            prevHadUpper = false,
            last         = null,
            lookFor      = '';
    
        while(!found && position < elements) {
            element = characterGroups[position].split('');
    
            if(element.length > 0) {
               last = element[element.length-1];
    
               // test last character rule
               if(
                  last=='.' ||                // ends in '.'
                  last=='!' ||                // ends in '!'
                  last=='?' ||                // ends in '?'
                  (last=='"' && prevHadUpper) // ends in '"' and previous started [A-Z]
               ) {
                  found = true;
                  index = position-1;
                  lookFor = last+' '+characterGroups[position-1];
               } else {
                  if(element[0] == element[0].toUpperCase()) {
                     prevHadUpper = true;
                  } else {
                     prevHadUpper = false;
                  }
               }
            } else {
               prevHadUpper = false;
            }
            position++;
        }
    
    
        var trimPosition = string.lastIndexOf(lookFor)+1;
        return string.substr(0,trimPosition);
    }
    

    It’s trivial to make a plugin for it if, but beware the ASSUMPTIONS! 🙂

    Does this help?

    Thanks,
    AE

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a bunch of posts stored in text files formatted in yaml/textile (from
For some reason, after submitting a string like this Jack’s Spindle from a text
I'm making a simple page using Google Maps API 3. My first. One marker
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I need to clean up various Word 'smart' characters in user input, including but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.