Break after second word and tinting

I am working with a product title "Pillow BALANCE purple" and I would like to have a line break after the second word. It should look like this:

Pillow BALANCE
purple

The title has a class called "title". I am currently using the following code to change the color of the first word "Pillow", but I also need to change the color of the second word and ensure that the third word goes to a new line. Any assistance on how to accomplish this would be greatly appreciated.

//add span to first word of module title, page heading
window.addEvent ('domready', function () {
    var els = $$('.art-postcontent h2 a, .art-postcontent h2 a:link, .art-postcontent h2 a:hover, .art-postcontent h2 a:visited, .art-blockcontent h2 a, .art-blockcontent h2 a:link, .art-blockcontent h2 a:hover, .art-blockcontent h2 a:visited');
    if (!els.length) return;
    els.each (function(el){
         var html = el.innerHTML;
         var text = el.get("text");
         var pos = text.indexOf(' ');
         if (pos!=-1) {
            text = text.substr(0,pos);
         }
         el.set("html", el.get("text").replace(new RegExp (text), '<span class="first-word">'+text+'</span>'));

    });
});

Answer №1

To solve this problem, try utilizing the split() method.

let text = 'apple SNACK blueberry';
let fragments = text.split(' ');    //separates the string into individual words at each space

$('#firstPart').text(fragments[0] + fragments[1]);  //combines first two words and displays on the first line
$('#secondPart').text(fragments[2]);  //displays the third word on the second line

HTML:

<div id="firstPart"></div>
<br />     <!-- The line break will move the following div to a new line -->
<div id="secondPart"></div>

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

Dealing with null exceptions in Angular 4: Best practices

Hi there, I am encountering an issue with binding my model data to HTML fields where when I try to edit the data it returns an error saying "cannot read value of null". How can I resolve this? Here is the HTML code snippet: <div class="form-group"> ...

Razor View does not support the activation of Javascript

I've been struggling to get some Javascript to work on a Razor View page, but for some reason it's not being activated. Any help would be greatly appreciated! Just a heads up: The View has a shared layout that loads jQuery & Bootstrap for all vi ...

Creating a Higher Order Component (HOC) for your Next.js page

Upon running the following code, I encountered an error message Error: The default export is not a React Component in page: "/" pages/index.tsx import React, { useState, useRef } from "react"; import type { NextPage } from "next&q ...

Creating a custom JavaScript function from a third-party source to mimic the behavior of an Angular2 HTTP request asynchronously

Currently, I am utilizing the AWS-SDK to facilitate the upload of images to an S3 bucket. The reason behind this choice is the absence of an Angular4 library tailored for this specific task as far as my understanding goes. The code snippet showcasing the f ...

Tips for disregarding modified configuration files in Git

I have a project stored in Git that I plan to install on numerous PCs. Within this project, there is a configuration file called config.ts with the following structure: export var config = { apiUrl: "", local: "", scannerUrl: "", reportPrinter ...

Understanding the Behavior of Vue 3's setInterval Methods

Environment I am working on a Vue 3 Application where I need to run a constant setInterval() in the background (Game Loop). To achieve this, I have placed the code in store/index.js and invoked it from views/Playground.vue's mounted() lifecycle hook ...

storing audio files locally with Vue.js

Looking for a way to store a sound locally for my Battleship game rather than referencing it on the internet. Here's the code that triggers the sound: @click.prevent="fireSound('http://soundbible.com/grab.php?id=1794&type=mp3')" I atte ...

(Javascript - Arrays) Find the leftmost and rightmost connected characters

Looking for the leftmost and topmost connected '1' character in a 2D matrix? Find the most left & top connected '1' character Find the most right & bottom connected '1' character EDIT 2.0: To start, provide the coordina ...

Please provide input when selecting an option from the dropdown menu

My invoice form includes a table with 3 columns: kode_barang (ItemID), nama_barang (ItemName), and qty (quantity). Currently, there are only 2 rows in the table: <form name="invoice" action="insert3.php" method="post"> <table id="theTable" border ...

Leveraging jQuery chosen for interactive form elements

This Table Row contains 5 input fields, with the first being a select box. I am utilizing the chosen jQuery plugin to enable search functionality for the select items. Since this is a dynamic form, I am duplicating these rows. However, I am facing an issu ...

Babylon entities failing to run

Encountering a strange issue in my current project. I am working on a react application that incorporates Babylonjs for 3D rendering. While I am able to successfully load objects into the scene, I am facing a problem when attempting to create a PBR Materia ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

The clear icon in React will only appear when there is a value inputted

Is there a way to implement the clear X icon that only appears when typing in the input field using reactjs, similar to the search input on the Google homepage? Check it out here: https://www.google.com import { XIcon } from '@heroicons/react/solid&ap ...

Navigate to the subsequent field in an HTML5 form without any manual intervention

I have created the following HTML5 form: <form> <input type="text" name="orderno" /> <input name="picture" id="img" type="file" accept="image/*" capture="camera" /> <input class="btn-success" type="submit" name="submit" value="Uplo ...

Transmission of state modifications in React

My React project is organized with the following hierarchy: The main A component consists of child components B and C If I trigger a setState function in component B, will components A and C receive notification and potentially re-render during the recon ...

Canvas in the off state has been removed

My goal is to create a basic JavaScript library that includes rotating, translating, and scaling the canvas. One issue I am facing is when I rotate the canvas, half of the content ends up getting deleted because the center of rotation is set at (0, 0). I ...

Creating custom transparency effects in Three JS using ShaderMaterial

When drawing two geometries next to each other and having them rotate, a common issue arises. The first drawn geometry obstructs the second one where transparency should be applied uniformly. Both objects should exhibit the same level of transparency regar ...

The function generalChannel.send does not exist

I've recently started working on a discord bot and I'm facing an issue with getting it to greet everyone when it's turned on. Using the bot.channels.get method, I am able to locate the channel successfully, but when it comes to sending a mes ...

Pressing either a left or right arrow to swap an element within an array with the adjacent element in a React application

As a newcomer to React, I'm currently working on creating an app that allows users to create cards, delete cards, and rearrange the order of the cards by clicking left or right arrows to switch elements with neighboring cards. However, I am facing cha ...

"Quickly clearing the terminal in Java Script with shortcut keys - a step-by-step guide

This GDS command is specifically designed to run on the Travelport terminal through API. Each command generates a response, and typing "clear" in the terminal will clear it. However, I am looking for a shortcut like (Ctrl + any key) to achieve the same fun ...