JavaScript function: Reduce array if total string length exceeds specified value using a loop

I am currently working on a function to shorten a text if it exceeds a certain length.

For example, calling shorten_text_easy(text, 30) should output

"We believe. In the future"
.

The initial loop is functioning correctly and showing the total length of the strings in the array accurately. However, I am encountering an error in the second loop and have been unable to pinpoint the issue.

var text = "We believe. In the future. The future is here. This is a test. We are testing.";

function shorten_text_easy(text, number) {
  var text_array = text.split('. ').join('.///').split('///'); // Breaking down the text into an array

  var text_array_length = text_array.length;
  var total_text_array_length = 0; // Initial value set to zero; represents the overall length of all strings in the array

  for (var i = 0; i < text_array_length; i++) { // Loop runs while i is less than the array's length
    total_text_array_length += text_array[i].length; // Adds up lengths of all strings
  }
  total_text_array_length = total_text_array_length + text_array_length - 1; // Adjusting for omitted spaces in the array
  console.log(total_text_array_length); // Displays the initial total length in the console

  for (total_text_array_length; total_text_array_length > number; text_array.pop(-1), text_array_length--) { // Aiming to remove the last item from the array if its total length exceeds 'number'
    for (var i = 0; i < text_array_length; i++) {
      total_text_array_length += text_array[i].length;
      console.log(total_text_array_length);
    }
    total_text_array_length = total_text_array_length + text_array_length - 1;
  }
  return text_array // Expected to return the final modified text array when the total string length is within the specified number
};
console.log(
  shorten_text_easy(text, 30)
);

Answer №1

Slicing at the last occurrence of a full stop

const shorten_text = (text, number) => {
  let res = text.slice(0,number);
  const pos = res.lastIndexOf(".");
  return pos > 0 ? res.slice(0,pos+1) : res;
}  
var text = "We believe. In the future. The future is here. This is a test. We are testing.";

console.log(
  shorten_text(text, 30)
);

Answer №2

This is the approach I took:

function truncateAtNextDot (text, length) {
    var firstDot = text.indexOf(".") + 1;
    if (length <= firstDot) {
        return text.slice(0, firstDot);
    } else {
        var textSnippet = text.slice(0, length);
        var remainingText = text.slice(length);
        var nextDotIndex = remainingText.indexOf(".") + 1;
        var truncatedText = textSnippet + remainingText.slice(0, nextDotIndex);
        
        return truncatedText;
    }
}

function truncateAtPreviousDot (text, length) {
    var firstDot = text.indexOf(".") + 1;

    if (length <= firstDot) {
        return text.slice(0, firstDot);
    } else {
        var textSnippet = text.slice(0, length);
        var lastDotIndex = textSnippet.lastIndexOf(".") + 1;
        var truncatedText = textSnippet.slice(0, lastDotIndex);

        return truncatedText;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble encountered while attempting to choose a single checkbox from within a v-for loop in Vue.js?

<div id="example-1"> <ul> <input type="text" v-model="searchString" placeholder="Filter" /> <p>sortKey = {{sortKey}}</p> <li v-for="item in sortedItems"> <input class="checkbox-align" type="checkbo ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Despite the false execution condition, the for-loop continues to increment

Being new to C programming, I'm facing an issue that seems simple but has stumped me. Despite hours of debugging, the output of my code is not what I expected. After investigating, I realized that one of my for loops is not working as intended. Here&a ...

The background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

Is it possible to transform a Vuejs project into Vue-Native?

I recently completed a Vue.js project and now I'm interested in turning it into a native app. I'm wondering if I'll need to completely rewrite the application using Vue-Native components, or if there is a way to convert my existing project i ...

Why won't my code execute in the script using Python's selenium function driver.execute_script()?

In my python script with the selenium library, I am encountering an issue with the driver.execute_script() function. It seems that only certain parts of the script are being executed while others are not. The following code works properly: driver.execute ...

What are the techniques for sorting and analyzing objects within an array?

I am working with a JSON structure that needs to be mapped, parsed, and filtered based on a specific attribute value. This process allows me to identify which object contains the desired value so I can access other attributes of the same object and impleme ...

What is the best way to insert an iframe using getElementById?

I am looking to make some changes in the JavaScript code below by removing the image logo.png lines and replacing them with iframe code. currentRoomId = document.getElementById('roomID').value; if ( document.getElementById('room_' + c ...

What is the best way to add a URL dynamically when a click event occurs?

Here is the code where I am making an API call: export const filteredProducts = (e) => { const radio = e.target.checked; return dispatch => { dispatch({type: actionTypes.TOGGLE_LOAD}); axios.get(radio ? `/store?limit=9&skip=0&subc ...

Is there a way to retrieve the Incoming Message object in Angular using HttpClient?

From my Angular file, I am sending this request to the server. Is there a way to access it from my typescript file using a HttpClient object? IncomingMessage { ... // Headers details omitted for brevity url: '/teradata/databases/view/djfg', ...

Dispatching actions in `componentDidMount` is restricted in Redux

Update at the bottom of post I've created a React container component called AppContainer, which checks if the user is authenticated. If the user is authenticated, it renders the app's routes, header, and content. If not, it displays a Login com ...

Using .substr method interferes with the functionality of the alert method

I've been struggling to extract the hours and minutes from a Microsoft JSON string. Despite reading through numerous articles, including How do I format a Microsoft JSON date?, I have not been successful. Even when attempting to implement the example ...

In JavaScript, where are the values saved?

Can you clarify how JavaScript handles storage for primitive types and objects? Are primitive types always stored on the stack and objects on the heap, even within the scope of a function's execution? Also, are globally scoped variables and functions ...

Rendering a ImageBitMap/Image on an OffScreenCanvas using a web-worker

In my vue.js application, I have implemented vue-workers/web-workers to handle image processing tasks such as scaling and cropping in the background after a user uploads images. Due to the lack of support for Canvas and Image Object in web workers, I opte ...

Displaying an RSS feed inside a designated div element

Seeking assistance from all you wonderful individuals for what seems to be a simple problem. Here is the HTML code I am working with: <div id="rssfeed"></div> Along with JavaScript that includes the FeedEK plugin $(document).ready(function ...

The result of list.append displays the term "collection" following every loop iteration

I need to create a Python list with entries that appear different numbers of times: import numpy as np frequency = (1, 2, 1, 2, 1) numbers = np.random.choice(9, size = (5, 3), replace=True) list_entries = [] for i in range(0, 5): list_entries.append( ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

Manually incorporating multiple React components into a single container

I am currently in the process of upgrading an old JavaScript application that relies heavily on jQuery by introducing some React components. The existing code utilizes JS/jQuery to dynamically add elements to the DOM, and I am looking for a way to replace ...

State in React Native causing asynchronous problems

I am working on developing a straightforward application that allows users to enter the name of a movie in a search bar. The app will then display a list of movies related to that specific title, sourced from an external public API. However, I have run int ...

Discover the method for retrieving the upcoming song's duration with jplayer

Hey there, I have a question regarding the jPlayer music player. Currently, I am able to retrieve the duration of the current song using the following code snippet: $("#jquery_jplayer_1").data("jPlayer").status.duration; However, I now want to obtain t ...