Issues with Jquery's Slice, Substr, and Substring functionalities

I need to divide the content into two separate sections. Unfortunately, the first variable (summarySentence1and2) is not capturing the desired result, while the second variable (summarySentanceOthers) is storing all of the content from the source field. I aim to split the content from 0 to 28 characters in the first variable and from 28 to the end in the second variable.

var summaryText = $(this).find('.review-body .field-name-field-review-summary').text();
var summarySentence1and2 = summaryText.split(' ').slice(0, 28).join(' ');
var summarySentanceOthers = summaryText.split(' ').slice(28).join(' ');

//alert(summarySentence1and2);
//alert(summarySentanceOthers);

$('#first').text(summarySentence1and2);
$('#second').text(summarySentanceOthers);
           
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="review-body" itemprop="reviewBody">
 <div class="field-name-field-review-summary">
We had an excellent guide in Antonino who took us on some excellent routes and had extensive knowledge of the area, fauna and history of the volcanoes and the evolution of the landscape. The hotels and included meals were disappointing and should have been of a higher quality.
</div>
</div>

<p id="first"></p>
<p id="second"></p>

Answer №1

Here is a revised version of the code I have adapted for you:

<script>

    $(document).ready(function () {
        var description = $(this).find('.review-body .field-name-field-review-description').text();
        var firstPart = description.split(' ').slice(0, 20).join(' ');
        var secondPart = description.split(' ').slice(20).join(' ');

        //alert(firstPart);
        //alert(secondPart);

        $('#first').text(firstPart);
        $('#second').text(secondPart);
    });


</script>

Answer №2

It seems like the issue you're experiencing is because your code is missing the jQuery document ready function

$(function() {
  var text = $(this).find('.review-body .field-name-field-review-summary').text();
  var sentence1and2 = text.split(' ').slice(0, 28).join(' ');
  var otherSentences = text.split(' ').slice(28).join(' ');

  $('#first').text(sentence1and2);
  $('#second').text(otherSentences);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="review-body" itemprop="reviewBody">
  <div class="field-name-field-review-summary">
    We had an excellent guide in Antonino who took us on some excellent routes and had extensive knowledge of the area, fauna and history of the volcanoes and the evolution of the landscape. The hotels and included meals were disappointing and should have
    been of a higher quality.
  </div>
</div>

<p id="first"></p>
<p id="second"></p>

Answer №3

To accomplish this task, you have two options:

var summaryText = $('body').find('.review-body .field-name-field-review-summary').text();

Alternatively, you can use:

var summaryText = $('.review-body .field-name-field-review-summary').text();

The this reference in your code points to the window object, which is unaware of the content within the body.

var summaryText = $('.review-body .field-name-field-review-summary').text();
var summarySentence1and2 = summaryText.split(' ').slice(0, 28).join(' ');
var summarySentanceOthers = summaryText.split(' ').slice(28).join(' ');

console.log(summarySentence1and2);
console.log(summarySentanceOthers);

$('#first').text(summarySentence1and2);
$('#second').text(summarySentanceOthers);
.as-console-wrapper { display: none !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="review-body" itemprop="reviewBody">
  <div class="field-name-field-review-summary">
    We had an excellent guide in Antonino who took us on some excellent routes and had extensive knowledge of the area, fauna and history of the volcanoes and the evolution of the landscape. The hotels and included meals were disappointing and should have
    been of a higher quality.
  </div>
</div>

<p id="first"></p>
<p id="second"></p>

Answer №4

After carefully considering your question, I recommend using the code "$('.review-body').text();" instead of "$(this).find('.review-body .field-name-field-review-summary').text();"

var summaryText = $('.review-body').text();
var summarySentence1and2 = summaryText.split(' ').slice(0, 28).join(' ');
var summarySentanceOthers = summaryText.split(' ').slice(28).join(' ');

//alert(summarySentence1and2);
//alert(summarySentanceOthers);

$('#first').text(summarySentence1and2);
$('#second').text(summarySentanceOthers);
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="review-body" itemprop="reviewBody">
 <div class="field-name-field-review-summary">
We had an excellent guide in Antonino who took us on some excellent routes and had extensive knowledge of the area, fauna and history of the volcanoes and the evolution of the landscape. The hotels and included meals were disappointing and should have been of a higher quality.
</div>
</div>

<p id="first"></p>
<p id="second"></p>

Answer №5

Fixing the problem by including .trim()

var summaryText = $(this).find('.review-body .field-name-field-review-summary').text().trim();

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

Enabling and disabling contenteditable functionality on a div element in Angular

Issue I am facing an issue while trying to bind a boolean to the contenteditable directive of a div. However, it seems that this binding is not working as expected. Error Message: The 'contenteditable' property is not recognized as a valid p ...

Need for Jekyll to Incorporate "excerpt" Liquid Tag in YAML Front Matter

My blog is running on Jekyll 3.0.1, using the Kasper theme with some custom modifications. I've cleared all the posts except one to simplify the issue I'm facing. The site builds correctly when I add an "excerpt" tag with a value in the post&apos ...

What could be the reason for PassportJS in Node failing to clear the session upon logout?

I am encountering an issue with my system not successfully logging out using PassportJS. The logout route appears to be triggered, but the session is not being removed as intended. I would like it to return a 401 error if the user is not logged in on a spe ...

JavaScript hack for improving slow scrolling experience with smooth scroll on Firefox

As a web application developer, I encountered a particular scenario where there are multiple position:fixed elements, canvases, and an overflow:scroll element. Unfortunately, scrolling in Firefox becomes extremely slow when smooth scrolling is enabled. Wh ...

What is the method to adjust the font size for section, subsection, and other sections in Doxygen?

I am looking to customize the font size of \section and \subsection in doxygen's html output. Additionally, I want to include numbering for the sections and sub(sub)sections in the format: 1 Section1 1.1 Subsection1.1 1.1.1 Subsubsection ...

Tips for transforming information into JSON format

Imagine having a file with data in CSV or TXT format, such as: Name, Surname, Age, Occupation Gino, DiNanni, 19, Student Anna, Kournikova, 27, Programmer (Extra spaces have been added to enhance readability) The goal ...

Troubulation with z-index on HTML5 Canvas in Google Chrome

After some testing, I've discovered that giving a canvas a z-index with the CSS property position:fixed in Chrome can cause rendering issues for other elements with the same position fixed. Interestingly, this problem only arises when the canvas excee ...

Unusual Conduct when Interacting with ContentEditable Text

Looking for help with a strange issue that I can't seem to figure out. Hopefully someone has encountered this before and might have a solution. In my Angular app, I'm using a contenteditable <div> for inputting content, which is working fi ...

Hide content when clicking on the body

I have successfully implemented a collapsible sidebar triggered by a single button using the code below: <a class="btn btn-tocanvas-report" href="#" id="btnOpenSidebarListMenuReport" role="button" aria-controls=&q ...

sending a file to a controller without the use of a form

Hey there, I'm exploring a way to transfer a file from a view to a controller without using a form. My goal is to enable the user to browse for a file and have it sent to the controller via Ajax. Do you think this is achievable? <td>Import ...

Navigating through the website has become quite challenging due to the malfunctioning navigation bar. Instead

I recently completed a website and designed an awesome navigation bar in a separate file. However, when I combined them together, the navigation bar disappeared. The background of my "list" div should be filled in and larger, but it's not working as e ...

Issue with the side panel: unable to close it

There seems to be an issue with the close button on the sidebar—it's neither displaying nor functioning properly. The show sidebar feature works perfectly fine, but there is a problem with the closing function. Below is the HTML, CSS, and JavaScript ...

Is there a way to have a button function as a submit button for a form even when it is located in a separate component within a react application?

I am in the process of creating a user-friendly "My Account" page using react, where users can easily update their account information. I have divided my components into two sections: the navbar and the form itself. However, I am facing an issue with the s ...

Using the toggle method or IF statements in JavaScript to implement show and hide functionality upon clicking

I’ve been struggling with this issue for days now. It seems like I may have overcomplicated a simple piece of code. I'm trying to show some divs when a button is clicked, but I’m having trouble getting it to work properly. Initially, I used VAR.st ...

Create a Bootstrap Affix that sticks the header at the top of the page after scrolling 100

Currently, I am implementing Bootstrap Affix on my header with the intention of making it fixed after scrolling 100px down the page. Here is the jQuery code snippet I have incorporated: $('#navbar').affix({ offset: { top: 100, ...

What is the best way to align the right column section below the left column section on a reduced screen size in a responsive design?

When the screen size is small, I want the "left-side" of my project to be displayed above the right side. The problem I'm facing is that as the screen shrinks, the left side starts getting hidden by the right side until it suddenly jumps to the right ...

Is there a way to easily access the automated departure range feature of a date

I apologize if my question seems too simple, but I am having trouble understanding JavaScript. My issue pertains to a range datepicker where I want the departure picker to automatically open when the arrival is selected. Here's the JavaScript code I h ...

What is the best way to resize images while also maintaining their ability to transition on hover?

Having an interesting dilemma here.. I'm trying to utilize this CSS code: .custom-forums { height: auto; width: 100%; border-image-source:transparent url("../images/forums.png") center top no-repeat; } in combination with: .custom-forum ...

My custom Material UI table is being hindered by unnecessary div tags that are interfering with my CSS styling

View the generated code The rendered table demonstrates that when scrolling past the maximum width, the data does not appear <div> <table (not going to display all the markup for this. this table contains the headers of each column and appear ...

Using Three.js to turn an object around its Y-axis to face a specific direction

After pondering over it for a week, I realized that the concept is too complex for me to grasp. The issue I am facing is when I click on specific coordinates on the plane, I want my 3D model to rotate towards those coordinates and then move to match them ( ...