Using JavaScript to place a particular tag at a designated position

I have a string that looks like this:

var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>';

I have an <img src=..../> tag and I want to insert it at a specific position within a p tag.

For example, let's say the 5th <p> tag and after the 7th character. Here, each &nbsp; will count as one character only, even if there are multiple instances of &nbsp;.

I tried doing something like this:

const paragraphs = str.split("</p>")
const firstParagraph = paragraphs[5]+'</p>';

but unfortunately, this method did not work as expected.

If anyone has a solution, I would greatly appreciate it. Thank you!

Answer №1

Thank you for checking this out.

// Here is a sample HTML string
var txtstr = "<p>Example Text 1</p><p>&nbsp;</p><p>Example Text &nbsp;2</p><p>&nbsp;</p><p>Example Text 3&nbsp;</p>";

// Specify where to insert the <img> tag (for example, after the 5th paragraph)
const insertPosition = 4;

// Define the image source
const imgSrc = "path/to/your/image.jpg";

// Generate the <img> tag
const imgTag = `<img src="${imgSrc}" />`;

// Split the text into paragraphs
const paragraphs = txtstr.split("</p>");

// Insert the <img> tag at the specified position
if (insertPosition >= 0 && insertPosition < paragraphs.length) {
  paragraphs[insertPosition] += ` ${imgTag}`;
}

// Combine the paragraphs back together to form the updated HTML string
const modifiedTxtstr = paragraphs.join("</p>");

console.log(modifiedTxtstr);

The resulting output will look like this:

<p>Example Text 1</p><p>&nbsp;</p><p>Example Text &nbsp;2</p><p>&nbsp;</p><p>Example Text 3&nbsp; <img src="path/to/your/image.jpg" /></p>

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 arises when emitting events in Vue using eventHub

In the development of my component, there arises a need to emit an event at a specific point in its lifecycle. This emitted event is intended to be listened to by another sibling component. To facilitate this communication, I am utilizing an event hub. H ...

Triggering an event upon selecting a dropdown option

I'm currently working on a form that includes a dropdown menu. My goal is to display specific keywords for each trip when selected from the menu (preferably below the input field, as shown in the code snippet below). .show has been set to display:non ...

AngularJS File Input element triggering only once when selecting the same file

I have created an Angular directive to customize the file upload input. directive('ngFile', function () { return { link: function (scope, element, attrs) { var button = element.find('button[data-fileInputButton]&apos ...

Three.js - Optimizing and Handling Images - Best Practices

My current project has a unique concept: https://i.sstatic.net/Jd3Ot.jpg The main idea revolves around a virtual room that dynamically adjusts its height based on the number of images loaded by the user. While it functions smoothly with fewer pictures, ...

The functionality of Jquery datatables seems to be faulty when navigating to the second page

While utilizing the jQuery datatables plugin, I encountered an issue where the event click function only worked on the first page and not on subsequent pages. To address this problem, I discovered a helpful resource at https://datatables.net/faqs/ Q. My ...

Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python. def func(A): result = 0 ...

What is the best way to retrieve a particular field from a Firestore Document using JavaScript?

Within my Firestore database, I have a structure of users that looks like this: The rules set up for this database are as follows: match /users/{userID} { match /public { allow read: if request.auth != null; } match /private/ ...

Mapping JSON data from Mongoose to Vue and Quasar: A comprehensive guide

I have set up a Mongoose backend and created some REST APIs to serve data to my Vue/Quasar frontend. The setup is pretty basic at the moment, utilizing Node/Express http for API calls without Axios or similar tools yet. I have successfully implemented simp ...

Using the forEach method, we can create multiple buttons in ReactJS and also access the onClick handler

I have a button with both the label and onClick properties. Additionally, I have an array containing the values I need to assign to the label property. Here is the code snippet: render(){ {tabel_soal.forEach(function (item, index) { <Ra ...

My ejs page is not showing up because a variable has not been defined

I am facing an issue with an undefined variable causing my EJS page to not display properly when an if statement is included. Removing the if statement allows the page to render, but the presence of the undefined variable and if statement triggers an error ...

A guide on trimming content with v-if in Vue.js

Recently, I attempted to trim the response value within a Vue condition. I require this functionality to apply the condition when the value is null or empty. <li v-if="item[0].otrodl4.trim() == ''" class="progress-step"> ...

Does this task require a high amount of CPU resources for Node.js on the back-end?

I am currently developing an Android app and I am faced with a decision on whether to utilize node.js or PHP for the back-end. The task at hand involves users inputting query parameters, such as zip codes, which are then used to perform database queries ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

Unable to access npm run build on localhost

I have developed a web application using react and node.js, and now I want to test it with a production build. After running npm run build in the app directory, I successfully created a build folder. However, when trying to run the application using local ...

securely managing file access through lockfile.locksync in node.js

Currently, I am utilizing lockfile.locksync to secure a file in my node.js application. However, I am interested in understanding the inner workings of this utility in more detail. Despite multiple resources referring to it as a "very polite lock file util ...

Instructions for removing all entries from a DynamoDB table

I am facing a challenge with deleting multiple items from a DynamoDB table. While the documentation suggests dropping and recreating the whole table, I want to avoid this approach as my table was created using AWS Amplify and I don't want to risk disr ...

Use an extension module in a Node.js script

I am currently working on integrating babylon.js into my Node.js Angular application. Current Integration Process 1) I have installed the babylon.js npm repository in my project's node modules using npm install --save babylonjs. The image below i ...

Tips for enabling mouse functionality while utilizing PointerLockControls

I'm currently working on a 3D art gallery using Three.js and PointerLockControls for navigation. My goal is to have the artwork on the gallery walls clickable, triggering a pop-up window with additional information. However, it seems that PointerLock ...

Converting JSON objects into TypeScript classes: A step-by-step guide

My challenge lies in converting Django responses into Angular's User array. This conversion is necessary due to variations in variable names (first_name vs firstName) and implementing specific logic within the Angular User constructor. In simple term ...

Switching video sources with jQuery and HTML5 can be achieved by clicking on an

I need to develop an engaging video using HTML5 and jQuery. My objective is to: Start playing video1 Show button1 when video1 finishes, then switch to video2 upon clicking and hide button1 Play video2 Display button 2 after video2 ends, then change to vi ...