substituting symbols with colorful divs

I'm looking to add some color to my text using specific symbols.

(), ||, and ++ are the symbols I'm using.

If a text is enclosed in | symbols, it will appear in blue, and so on...

Here is the code in action:

const text = "|Working on the| ideas |above|, and if you're working " + 
    "with a form, you can define a hidden input and assign it a " + 
    "value |of the last| focused input Working on the ideas above, " + 
    "and if you're working with a form, you can define a hidden |input " + 
    "and assign| it a value of the last focused input Working " + 
    "on the ideas above, and if you're working with a |form,| " + 
    "you can define a hidden input and assign it |a| value of the " + 
    "last |focused input|";

const contentArea = document.getElementById('contentArea')
let render = '';

render += getColored(text);


contentArea.innerHTML = render;


function getColored(text) {
  let result = text;
  result = result.replace(/\|([^|]+)\|/g, '<span class="blue-string">$1</span>');
  result = result.replace(/\(([^|]+)\)/g, '<span class="red-string">$1</span>');
  result = result.replace(/\+([^|]+)\+/g, '<span class="orange-string">$1</span>');
  return result;
}
.blank {
   display: inline-block;
   border-bottom: 4px dotted red;
   width: 150px;
}

.blue-string {
  font-family: "Vazir";
  color: #7e7cff;
  display: inline-block;
  text-shadow: 0px 0px 1px #010076;
}

.red-string {
  font-family: "Vazir";
  color: #ff005e;
  display: inline-block;
  text-shadow: 0px 0.5px 1px #e40053;
}

.orange-string {
  font-family: "Vazir";
  color: #ffb000;
  display: inline-block;
  text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></div>

Everything seems to be working fine with the | symbol highlights. However, when using () and ++ symbols with multiple occurrences, distortions occur. Take a look at this:

const text = "|Working on the| ideas |above|, and if you're working " + 
    "with a form, you can define a hidden input and assign it a " + 
    "value |of the last| focused input Working on the ideas above, " + 
    "and if you're working with a form, you can define a hidden |input " + 
    "and assign| it a value of the last focused input Working " + 
    "on the ideas above, and if you're working with a |form,| " + 
    "you can define a hidden input and assign it |a| value of the " + 
    "last |focused input|";

const contentArea = document.getElementById('contentArea')
let render = '';

render += getColored(text);


contentArea.innerHTML = render;


function getColored(text) {
  let result = text;
  result = result.replace(/\|([^|]+)\|/g, '<span class="blue-string">$1</span>');
  result = result.replace(/\(([^|]+)\)/g, '<span class="red-string">$1</span>');
  result = result.replace(/\+([^|]+)\+/g, '<span class="orange-string">$1</span>');
  return result;
}
.blank {
   display: inline-block;
   border-bottom: 4px dotted red;
   width: 150px;
}

.blue-string {
  font-family: "Vazir";
  color: #7e7cff;
  display: inline-block;
  text-shadow: 0px 0px 1px #010076;
}

.red-string {
  font-family: "Vazir";
  color: #ff005e;
  display: inline-block;
  text-shadow: 0px 0.5px 1px #e40053;
}

.orange-string {
  font-family: "Vazir";
  color: #ffb000;
  display: inline-block;
  text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></div>

It seems that using multiple instances of () symbols causes unexpected behavior. If I'm following the same pattern for |, (), and ++ symbols, why does this issue occur and how can it be fixed?

NOTE: The same distortion occurs when using the + symbol.

Answer №1

There is a mistake in your regular expression pattern. When using |...| delimiters, you correctly set \|([^|]+)\| to match all non-pipe characters between the pipes.

However, for +...+ delimiters, you mistakenly set \+([^|]+)\+ to match all non-pipe characters between pluses. The correct pattern should be \+([^+]+)\+.

Similarly, for (...) delimiters, you incorrectly set \(([^|]+)\) to match all non-pipe characters between parentheses. The correct pattern should be \(([^)]+)\).

const text = "(Working on the ideas above), and |if| you're +working+ with a form, you can define a hidden input and assign it a value of the last focused input Working on the ideas above, and if you're working with a form, you can define a hidden input and assign it a value of the last (focused) input Working on the ideas above, and if you're working with a form, you can define a hidden input and assign it a value of the last focused input";

const contentArea = document.getElementById('contentArea')
let render = '';

render += getColored(text);


contentArea.innerHTML = render;


function getColored(text) {
    let result = text;
        result = result.replace(/\|([^|]+)\|/g, '<span class="blue-string">$1</span>');
        result = result.replace(/\(([^)]+)\)/g, '<span class="red-string">$1</span>');
        result = result.replace(/\+([^+]+)\+/g, '<span class="orange-string">$1</span>');
        return result;
}
.blank {
   display: inline-block;
   border-bottom: 4px dotted red;
   width: 150px;
}

.blue-string {
  font-family: "Vazir";
  color: #7e7cff;
  display: inline-block;
  text-shadow: 0px 0px 1px #010076;
}

.red-string {
  font-family: "Vazir";
  color: #ff005e;
  display: inline-block;
  text-shadow: 0px 0.5px 1px #e40053;
}

.orange-string {
  font-family: "Vazir";
  color: #ffb000;
  display: inline-block;
  text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></div>

Answer №2

To match the least number of characters possible, you can utilize a lazy quantifier ?. With this regex pattern, you can easily identify the next symbolic pair:

const text = "(Implementing the concepts mentioned above), if you're |working| on a project, you might consider defining a hidden field and giving it the value of the latest selected input Implementing the concepts +mentioned+, if you're |working| on a project, you might consider defining a +hidden field and giving+ it the value of the latest selected input +Implementing the concepts mentioned+, if you're working on a project, you might consider defining a |hidden field and giving| it the value of the latest (selected) input +Implementing the concepts mentioned+, if you're working on a project, you might consider defining a |hidden field and giving| it the value of the latest (selected) input";
const contentArea = document.getElementById('contentArea');

const getColored = text => text.replace(/\|(.+?)\|/g, '<span class="blue-string">$1</span>')
  .replace(/\((.+?)\)/g, '<span class="red-string">$1</span>')
  .replace(/\+(.+?)\+/g, '<span class="orange-string">$1</span>')
  .replace(/_+/g, "&nbsp;<span class='blank'></span>&nbsp;");

contentArea.innerHTML = getColored(text);
.blank {
  display: inline-block;
  border-bottom: 4px dotted red;
  width: 150px;
}

.blue-string {
  font-family: "Vazir";
  color: #7e7cff;
  display: inline-block;
  text-shadow: 0px 0px 1px #010076;
}

.red-string {
  font-family: "Vazir";
  color: #ff005e;
  display: inline-block;
  text-shadow: 0px 0.5px 1px #e40053;
}

.orange-string {
  font-family: "Vazir";
  color: #ffb000;
  display: inline-block;
  text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></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

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

Issue with onClientClick not functioning properly when performing a jQuery function call

How can I make a jQuery form appear when an ASP.NET server-side button is clicked by the user? Currently, when I click on the button during runtime, the page reloads quickly without displaying the jQuery form. I am aiming to achieve a similar effect show ...

What is the best method for removing extra spaces from an input field with type "text"?

I have an input field of type "text" and a button that displays the user's input. However, if there are extra spaces in the input, they will also be displayed. How can I remove these extra spaces from the input value? var nameInput = $('#name ...

Why is the response undefined when I resize an image twice using a JavaScript promise chain?

When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize and .toBuffer() multiple times is causing corruption in th ...

The Discord.js collector seems to have no intention of ending, completely disregarding its keys in order

Help Needed with Discord Message Collector Issue I encountered a problem with my code that assigns ranks on Discord. It seems that the message collector is not responding to keys that should stop it from collecting messages. Can anyone offer assistance in ...

Change a CSV string into a JSON array and assign it to a variable

I am working with JSON data that looks like this: [ { "Title": "PAGE A", "Users": "USRA" }, { "Title": "PAGE B", "Users": "USRA,USRB" } ] What is the most efficient method to convert the fields containing " ...

Using JavaScript closures together with a timeout in the onKeyUp event

My goal is to add an onKeyUp event to all input fields within a form using closures. The array fields holds the names of the fields that need this event, while the array ajaxFields contains the names of fields requiring ajax validation. function createEve ...

Is there a way to modify the variable in order to switch the font of the heading every second using CSS and JavaScript?

I'm trying to create a heading that changes fonts every second, but I'm having trouble changing the variable to set it to another font. Check out my code here. Despite watching tutorials, everything seemed too confusing. var root = document.q ...

What's causing the text not to wrap when using float?

I've tried setting float:left for the image and float:right for the text, but the image is still overlapping the text. What I really want is for the text to wrap around the image - to be on the right side of the image at the beginning and below the i ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

"Learn the process of converting HTML content into a string in an Android application and then displaying

I utilized this/this to Print Receipts in part of POS(Point of Sale) from EPSON Printer Obtaining data Json from URL (within the Json Object is html print template): { "response": { "status": "<table>.... </table>" } } Hence, ...

Trouble with CSS display in Internet Explorer 8

My website located at this link is working perfectly in IE 10 and IE 11, however, any version lower than that is causing the content to be displayed on the far left of the screen instead of centering it. I have tried tweaking the CSS but can't seem to ...

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

Activating/diverting DIV elements through specific functions (on a WordPress website)

I have a stronger background in HTML and CSS, but I'm struggling with coding the functionality I want to see on a WordPress page. My goal is to create a page that displays upcoming events for a specific province or region of Canada, with an interactiv ...

Ways to identify whether a div is in view and includes an input field

This is a unique question that is not related to the issue of querySelectorAll detecting value in input. Instead of asking whether an input field has a value, I am interested in how to detect if the current visible div contains an input field. This is a n ...

Setting up vue-apollo 3.0.0 Beta

Seeking guidance as a newcomer in this field. I have experience with Authentication using Apollo client, but I'm stuck when trying to integrate the new vue-apollo-plugin into my Vue-cli-3 generated project. Specifically, I'm confused about how an ...

Updating Checkbox Appearance in Angular 6 Based on its Checked Status

I have created a checkbox list and I am trying to style the checked item with an underline. Here is my code snippet: TS file: currentQuarter: string; quarters: Observable<MeseRiferimento[]>; q1: MeseRiferimento = new MeseRiferimento(); q2: MeseRife ...

Receive characteristics in component specification

Is there a way to pass the native attributes of an img element to a custom image component without explicitly defining each one, like alt, and have them all be applied to the img tag? Here is an example of what I mean: @Component({ selector: 'image ...

Triggering the hidden radio button with an OnClick event

I am using the Bootstrap framework to design my user interface. I have a specific requirement where I need to display multiple buttons that function as radio buttons. <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary a ...