What is the best way to locate all complete words within a string, up to 65 characters in length?

Looking to enhance my titles for better Google SEO (using title tag in html).

My product titles are currently 3-4 lines long and do not look appealing. I am looking for a way to identify the last complete word before the 65th character in a string.

For example, if 'foo bar baz buzz' is part of a lengthy string and the "a" in "baz" happens to be the 65th character, I aim to exclude just "baz" and everything beyond it.

Answer №1

This is the solution I ultimately decided on:

function shortenTitle(text, length = 60) {
  // Create a temporary substring with the specified length
  if (text.length <= length) {
    return text;
  }

  const tempSubstr = text.substr(0, length);

  // Find the index of the last space character
  const lastSpaceIndex = tempSubstr.lastIndexOf(' ');

  // Return the final shortened substring
  return tempSubstr.substr(0, lastSpaceIndex).trim();
}

Answer №2

After looking at the different solutions, I've decided to take my own approach.

One key observation I made is that if the last word is complete, there should always be a space after it.

Therefore, all you have to do is increase your desired length by +1. If the 66th character happens to be a space, then the last word before it is complete and you shouldn't remove it. But if it's not a space, then it should be discarded.

In situations where the last character is a space, when you .split() based on spaces, an empty string will be created as the last element because the final space acts as the point of separation - allowing you to safely .pop() the last element knowing it's either incomplete or empty.

Example code snippet

// Generate a long string with the entire alphabet
var str = new Array(100).fill('abcdefghijklmnopqrstuvwxyz').join(' ');

// Specify the last character to consider
var len = 65;

// Split the string at the specified length + 1
var words = str.slice(0, len + 1).split(/\s+/);

// Remove the last element, which is either empty or incomplete
words.pop();

// Only full alphabets will be displayed
console.log(words);

Answer №3

Firstly, ensure that the string exceeds the required length before proceeding with the following steps...

let text = "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.";

const char_limit = 50;

//create a temporary substring of the specified length
let temp_text = text.substr(0, char_limit);

//locate the last space in the temporary substring
let last_space_index = temp_text.lastIndexOf(" ");

//generate the final shortened string
let short_text = temp_text.substr(0, last_space_index).trim();

//process completed

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

Merging two divs in AngularJS

Currently in the process of converting an application from jQuery to AngularJS, I'm faced with a challenge involving combining two twin beds into a king bed using a bootstrap button toggle. Let's simplify this scenario by imagining two rounded bo ...

Divide a string into separate numbers using JavaScript

This snippet of code is designed to search the table #operations for all instances of <td> elements with the dynamic class ".fuel "+ACID: let k = 0; let ac_fuel = 0; parsed.data.forEach(arrayWithinData => { let ACID = parsed.data[k][0]; ...

Retrieve specialized information from a json file

I have a JSON variable called json which contains some data in JSON format. I am attempting to extract a specific portion of that data. One way to do this is by using the index as demonstrated below: var newdata = json[listid].Taxonomies[0]; However, my ...

Adding static files to your HTML page with node.js

This is not a question about using express.static() In my application, I have multiple pages that share the same JS and CSS dependencies. Instead of adding <script> or <link> tags to every single page, I'm looking for a way to include the ...

Hiding icons in a jquery datatable's table

I am currently developing an inline editing feature, and I would like to display a green checkmark in a column cell to indicate that the record has been updated. However, I need to hide it initially. This is how it looks at the moment: https://i.sstatic. ...

What is the best way to store client-uploaded files on the client-side using Bootstrap forms and Express server code?

Essentially, the user submits a file for upload, which is then saved on the client-side (I believe this is handled by PHP), and the upload form I am utilizing is a Bootstrap HTML form. On the server side, I am writing my code with Express. I'm feeling ...

What is the best method for resizing an SVG according to the size of my website's window?

I am attempting to implement a scalable settings icon SVG file that adjusts based on the window width. My approach involved creating a JavaScript function that alters the element's dimensions according to the window size, but unfortunately, this metho ...

Combining the power of Angular with a Vanilla JS web application

Seeking your expertise. Situation We are transitioning from a legacy Vanilla JS webapp to Angular. Our plan is to gradually replace isolated components while adding new functionality as separate Angular apps, all within a timeframe of 6-12 months. Challe ...

Insert information into a nested array using Mongoose

I'm encountering an issue with my code, even though I know it may be a duplicate. Here is the snippet causing me trouble: exports.addTechnologyPost = function(req, res){ console.log(req.params.name); var query = { name: 'test ...

What distinguishes calling the toString() method from simply using it?

After running multiple tests, I have not been able to identify any noticeable distinctions. const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); Along with const fruits = ["Banana", "Orange" ...

Having trouble with Vuex actions. Getting an error message that says "Failed to signInWithEmailAndPassword: The first argument "email" must be a valid string."

I recently started exploring Vuejs state management. I attempted to create a login system with Firebase using Vuex. However, I encountered the following error: signInWithEmailAndPassword failed: First argument "email" must be a valid string I'm havi ...

Determining the location of the cursor within 'ng2-ckeditor'

I'm a beginner with Angular 2 and I'm using 'ng2-ckeditor 1.0.7' in my Angular 2 application. The editor is functioning well within the app. However, I am now faced with the challenge of appending text at the cursor position. Unfortunat ...

Browsers are failing to display any content during ajax calls

I am currently attempting to extract artist URLs from the following page: https://myspace.com/discover/artists?genreId=1002532 However, this page is making an AJAX call to retrieve user details. I have identified the URL in Firebug as: https://myspace.c ...

Unable to post form attribute value after submission

I have created a form that looks like this: <form method="POST" action="create.php" data-id="0" class="postForm"> <input type="hidden" id="#formId" value="1"> <textarea class="formBodyText"></textarea> <button typ ...

Adjust the horizontal position of a text element using CSS

I am faced with a specific challenge where I need to center the text "test" within a text tag using only CSS, without being able to directly change the HTML. <text width="13.89" height="13.89" x="291.46999999999997" y="156.55" transform= ...

Running CesiumJS is a straightforward process that can be done by

After diligently following the provided instructions, I managed to get cesium running locally. I then attempted the hello world example as shown: However, despite clicking on "open in browser," I couldn't see anything. It has been a constant struggl ...

What are the benefits of using a synchronous XMLHttpRequest?

Many developers opt for asynchronous XMLHttpRequest requests, but the existence of synchronous requests suggests that there could be valid reasons for using them. What might those reasons be? ...

Transferring JavaScript to a different page using EJS

Feeling a little stuck here and could use some assistance. It seems like a simple issue, but I'm tired and could really use a fresh pair of eyes to take a look. I'm trying to pass the 'username' variable, but since I'm new to this ...

Upon sending an HTTP POST request from JavaScript to a Node server, the body was found to be

Trying to make an XMLHttpRequest from JavaScript to my node server. This is the request I am sending: var data = { "fname": "Fasal", "lname": "Rahman" }; var body = JSON.stringify(data); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/admin"); xhtt ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...