Divide the string into two equal sections with nearly identical lengths

Given a string: "This is a sample string", the task at hand is to split it into 2 strings without breaking any words. The goal is to create two strings with the closest length possible, resulting in:

["This is a", "sample string"].

For example:

"Gorge is nice" => ["Gorge", "is nice"]

It would also be helpful if the function could accept the number of elements as a parameter and provide the desired result accordingly.

Appreciate any assistance provided!

Answer №1

To locate the next occurrence of a particular string within a given text, you can utilize the indexOf function with the optional second parameter set to half the length of the string. This way, indexOf will start searching for the matching string from the index after the provided one.

Check out the live demonstration here.

var str = "Thisasdfasdfasdfasdfasdf is a sample string",
  len = str.length;

var ind = str.indexOf(' ', Math.floor(str.length / 2) - 1);
ind = ind > 0 ? ind : str.lastIndexOf(' ');

var str1 = str.substr(0, ind),
  str2 = str.substr(ind);

document.write(str1 + ' <br /> ' + str2);


LATEST UPDATE

If the necessity arises to divide the text into 3, 4, or any other number of elements, what would be the approach?

function split(str, noOfWords) {
  // Defaulting to splitting into 2 words if no specific number is provided
  noOfWords = noOfWords || 2;

  var len = str.length; // Length of the input string
  wordLen = Math.floor(len / noOfWords); // Approximate length of each word

  var words = [],
    temp = '',
    counter = 0;

  // Split the string by spaces and iterate over it
  str.split(' ').forEach(function(v) {
    // Recalculate the new word length
    wordLen = Math.floor((len - words.join(' ').length) / (noOfWords - counter));

    // Check if the current word length exceeds the limit
    if ((temp + v).length < wordLen) {
      temp += ' ' + v;
    } else {
      // Add the formed word to the array
      words.push(temp.trim());

      // Increment counter for word length calculation
      counter++;
      temp = v;
    }
  });

  // Handle the last element
  temp.trim() && words.push(temp.trim());
  return words;
}

var str = "This is a sample string. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos quae error ab praesentium, fugit expedita neque ex odio veritatis excepturi, iusto, cupiditate recusandae harum dicta dolore deleniti provident corporis adipisci.";

var words = split(str, 10);

console.log(words);
document.write('<pre>' + JSON.stringify(words, 0, 2) + '</pre>');

Answer №2

One option is to use a splitter function like the one demonstrated below:

function splitString(str) {
  var length = str.length,
    midpoint = Math.floor(length / 2);

  var leftIndex = midpoint - str.substring(0, midpoint).lastIndexOf(' '),
    rightIndex = str.indexOf(' ', midpoint) - midpoint;

  var index = midpoint + (leftIndex < rightIndex ? -leftIndex : rightIndex);

  return [str.substr(0, index),
    str2 = str.substr(index)
  ];
}

var segments = splitString("123-456 3-5-asldfkjas kdfasdfasd fjas");
snippet.log(segments[0]);
snippet.log(segments[1]);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Answer №3

Splitting words by space is a useful technique.

For example:

var words = 'George is nice'
words = words.split(' ')

You can then iterate through the array and compare string lengths. For instance:

var concat = ''
for (var word in words)
{
    word = words[word]
    if (word.length < words[word - 1] )
    {
        concat += word
    }
}

Why must it be just two elements, rather than the total number of words? Is there a specific algorithm you are aiming for? Or do you simply want to combine the shortest amount of text possible?

Understanding the purpose behind this requirement would be helpful.

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

Having trouble converting the JQuery result from the REST request into the correct format

Currently, I am working on making a REST request for an array of objects using JQuery. During the execution of the code within the "success" section, everything works perfectly fine - the objects in the array are converted to the correct type. However, I ...

The system encountered an error while attempting to access the property "getChild" of an unspecified object

I am currently developing a react application and encountering an issue when trying to call a function from the render method. The function I'm trying to call utilizes the getChild method, but I keep receiving an error stating "cannot read property &a ...

Is there a way to automatically remove a document in MongoDB and Node.js once its expiration date has passed?

I'm working on an appointment booking app and I need to automatically delete booking details after the booked date has passed. How can I make this happen? I attempted to use node-scheduler for this task, but it wasn't successful. The app itself ...

Vue.js fails to display multiple uploaded images

I have been working on implementing a multiple image upload feature using vue.js. So far, everything seems to be functioning correctly. However, I am facing an issue where the HTML does not display thumbnails of the images I have selected. Additionally, I ...

Using angularjs, populate a dropdown menu by enclosing the options in curly braces

Utilizing the curly braces syntax interpolation in AngularJS allows us to connect data from the model to the view. This technique is typically used for displaying text. Is there a way to populate a dropdown list using the {{}} syntax? ...

What is the process by which Next.js uses useRouter() to interpret the mapping variable?

const router = useRouter(); return ( <> {Usercategory.map((user,index)=>{ return <div className='user-li' key={index} onClick={()=>{router.push(user.link)}}> <li> {use ...

Utilizing Cordova for Windows 8.1 in Visual Studio 2015 for external image retrieval and insertion into img tag

I am encountering an issue with displaying external images in a Cordova app. While the DOM is functioning correctly, the images are failing to load. I am specifically trying to resolve this for Windows 8.1 only. In my Cordova project for JavaScript, I have ...

Is the text in bold format or not detectable in contenteditable mode?

I am currently working on developing a custom text editor using the built-in contenteditable feature in HTML. I am trying to figure out how to determine whether the selected text is bold or not within the editor. This is what my current setup looks like: ...

The search functionality in the table is experiencing a glitch where it does not work properly when trying to search with a

I created a simple mini-app with a search bar and a table displaying data. Users can enter keywords in the search bar to filter the data in the table using lodash debounce function for smoother performance. Everything works fine except for one issue - when ...

Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided. Input = "ABC DEF GHI" The generated code would look like, "ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters o ...

Retrieve the name of the selected checkbox

Currently, I am working on a page where check boxes are generated dynamically. Every time a user clicks on any of the check boxes, the following event is triggered: $(':checkbox').click(function() { }); I would like to know how I can retrieve ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

Connect guarantees while generating template

Fetching data through a function. Establishing a connection and retrieving necessary information. Some code has been omitted for brevity. function executeSQL(sql, bindParams , options) { return new Promise(function(resolve, reject) { ... resolv ...

Combining GET and POST requests in ExpressJS on a single route

As I work on setting up a questionnaire in Express JS with EJS as the renderer, I have already created individual pages for each question. These pages are accessible through static links using the app.get('/question/:number?', routes.questions) f ...

What is the process for changing the state of an array in graphql?

Currently, I am facing a challenge with adding an array to a GraphQl schema. Here is what it looks like: type Play { winRatio: [Float] } The intention behind the winRatio attribute is to store the history of all win ratios. For instance, after playing 3 ...

I am facing difficulties accessing an element within a controller in Angular

Struggling to access an element inside an AngularJS controller, I attempted the following: var imageInput = document.getElementById("myImage"); Unfortunately, this approach was unsuccessful as the element returned null. Curiously, when placing the statem ...

Exploring the capabilities of storing and retrieving nested objects within a React database

I'm having trouble retrieving nested items from my database. This is how my database is structured: GET /dwelling/room/ [ { "room_id": 1, "room_name": "Living Room", "room_data": [ { "id": 1, ...

Rearranging a JSON Object post editing

Currently, I am working on a project where I need to display and sort a list of items based on a JSON object. This includes sorting by both string values and integers within the object. So far, I have been successful in listing and sorting the items by st ...

Conditional rendering of a component in ReactJS while maintaining the "empty" space

Is there a way to conditionally render a component without affecting the layout of other components? I'm trying to avoid unwanted shifts caused by this div https://i.sstatic.net/g1eUd.gif Do you have any suggestions? Here is a snippet of my code: ...

Warning: The DataTables alert has been triggered for table ID DimStatus. It is indicating that an unknown parameter, 'Code', has been requested for row 0 and column 0 during the initialization

https://i.stack.imgur.com/yEpSp.pngI am encountering an error while attempting to display my data in a datatable. The structure of my table is as follows: [Table("DimStatus", Schema = "dmg")] public class PolicyState { [Key] ...