Swap out a term in a sentence with an interactive span element in real-time

I'm struggling with a seemingly simple task, and I feel quite embarrassed that I can't seem to solve it. My goal is to identify words in a string that begin with '@' or '#' and change their color to blue. The string itself comes from an API, so initially setting the word inside a span is not an option.

I attempted using the string method `replace()` with a regular expression to locate words starting with '@', and then replacing them with a span containing the same text colored blue. Although I've come across this solution multiple times on Stack Overflow, implementing it causes the entire span to render as text instead of just the content itself. Additionally, the font color remains unchanged – resulting in

<span style='color: blue;'>@user42</span>
being displayed rather than simply @user42.

While trying a different regex pattern to prevent spans from appearing as text on the page, it feels like I'm missing something crucial and performing unnecessary steps to address an unknown issue.

Here's my attempt at resolving this without using `.replace()`, but I'm struggling to place the newly created span back in the original position where the word was removed:

tweetText[0].split(' ').forEach((word) => {
  if (word.innerText.startsWith('@') || word.innerText.startsWith('#')) {
     const span = document.createElement('span');
     span.innerText = word;
     span.style.color = 'blue';
   }
 });

Could someone guide me on utilizing `replace()` effectively to identify words starting with '@' or '#' and replace them with the same text in a different color?

Answer №1

Enhanced the appearance by including color, background-color, padding, and border-radius styles.

const result = document.querySelector(".result");

function applyTextStyling(str) {
  const result = str
    .split(" ")
    .map((word) => {
      if (word.startsWith("@") || word.startsWith("#")) {
        return `<span style='color: blue; background: bisque; padding: 0.25rem; border-radius: 4px;'>${word}</span>`;
      }
      return word;
    })
    .join(" ");
  return result;
}

const text = applyTextStyling(
  "This is @test for the #color that is not colored"
);

result.innerHTML = text;
<div class="result"></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

How can I create a table that is 100% width, with one column that has a flexible size and truncates text

I am currently facing an issue with a table nested within a div that is absolutely positioned on my webpage. I want to set specific widths for the second, third, etc columns while allowing the first column to automatically resize, even if it results in tru ...

Send a vanilla JavaScript ajaxForm submission by completing the form

I am currently in the process of integrating JavaScript from an iOS application into a web application. I have control over the code for both apps. My objective is to develop a JavaScript function that can receive input from a barcode scanner, populate a w ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

Looking for assistance on how to use Express JS to make a post request to insert data with an array of objects into a database. Can anyone provide guidance?

While utilizing ExpressJS for serverside functionality, I encountered an issue when making a post call with multiple objects in an array. The error message displayed is as follows: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...

Is there a common method for generating complex identifiers to be used as the HTML element's id, class, or name attributes

Is there a recommended method for "encoding" complex identifiers such as {Source:"ARCH.1", Code: "456-789.456 A+", SubNumber:##2} to be used in HTML elements' id, class, and name attributes? I could come up with something myself, but perhaps there is ...

Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers. openPdf = () => { const sendObj = { ...

Encountering a Laravel Nova issue where attempting to override a Vue component leads to a Vue warning: Error

Recently, I decided to incorporate a user guide into my nova using the following Vue Shepherd library. To make this work, I made some adjustments in the files within the nova directory. One of these changes involved renaming the file "webpack.mix.js.dist" ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Modifying CSS stylesheet does not alter the background color

body { background-color: bisque; } <!DOCTYPE html> <html> <head> <title>Reading</title> </head> <body> <h1> <button><a href="index.html">Home</a></button> & ...

Is there a way to prevent the DOM from loading images until Angular has successfully injected the correct variables?

Having some trouble with this block of code I have: <div class="image" ng-repeat="image in images"> <img src="{{image.url}}"></img> </div> It seems that the image sources are being set correctly, but I keep getting an error wh ...

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...

How can I showcase data retrieved from a function using Ajax Datatable?

I have implemented an Ajax function that retrieves data from a PHP file and displays it in a DataTable. Initially, this setup was working fine. However, when I added a new function to the PHP file, my Ajax function stopped retrieving data from the file. I ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

Creating animated reactions in discord.js is a goal of mine, however, I am encountering an issue that needs to

Last year, I asked this question and received helpful answers. However, there is still a problem that I couldn't figure out. Since I am unable to comment on the previous answers, I have decided to add a new question client.on('message', mess ...

How can one keep object values constant or unchanging in JavaScript?

Here is a simple example where I need to clarify my requirement. I want to ensure that the values of object a are not changed after assigning it to constant b and modifying its values. I want the console to display the original values of object a, not the ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

Can you please tell me the font size specified as 20px/26px?

Recently stumbled upon the 20px/26px value in a codebase I'm currently working on. Wondering if anyone has encountered this before and knows what its purpose is. Interestingly, it renders with the latter pixel value (26px) in Chrome. #action { font: ...

Placing the date of each blog post at the end of the excerpt

Currently, there is a grid section on the homepage of our site showcasing the two most recent blog posts. I am looking for a Javascript solution to relocate the date to the bottom of each block, outside of the border. For reference, you can visit the follo ...

Display additional fields based on a condition in ASP.NET Core 6.0 MVC for a Yes/No input

If a user enters either Yes or No in a specific field, I want to display additional fields that need to be filled based on their choice. <div class="col-6"> <label for="Renda Bruta">Demonstrativo do Ano</label> ...