When comparing strings, if they match, replace them with bold text

Today, I faced a challenging brain teaser that kept me occupied for over an hour.

The task at hand is to compare two strings: the text input from the field and data-row-internalnumber. The goal is to determine if they match and then bold only the last letters in the field, while removing spaces and the + sign. It can be tricky since the spaces between the field and data-row-internalnumber don't always align perfectly. Although regex isn't my strong suit, I believe it can help streamline this code. Is there a more efficient way to tackle this with regex?

http://jsfiddle.net/kjarisk/7y9mX/

The desired output should display the field with bold endings if they match the data-row-internalnumber.

Below is the code snippet I came up with (simulated version using jQuery):

<ul>
        <li data-row-internalnumber="+123">+345 555 123</li>
        <li data-row-internalnumber="+2 002">+345 552 002</li>
        <li data-row-internalnumber="+135">+345 555 1135</li>
        <li data-row-internalnumber="123">+345 555 5123</li>
        <li data-row-internalnumber="21 3">+345 555 213</li>
        <li data-row-internalnumber="1 023">+345 551 023</li>
        <li data-row-internalnumber="500 1">+345 555 001</li>
        <li data-row-internalnumber="456">+456 555 4156</li>
        <li data-row-internalnumber="345">+345 555 345</li>
        <li data-row-internalnumber="3 333">+55 333333333</li>
        <li data-row-internalnumber="4 444">+4444 55 555</li>
    </ul>
    <script src="js/jQuery.js" type="text/javascript" charset="utf-8"></script>
    <script>
        $('li').each(function() {
            var attr = $(this).attr('data-row-internalnumber');
            if (attr !== undefined && attr !== "") {
                var totalLetters = 0, 
                numbers = [], 
                numbersMatch = true, 
                orginalText = $(this).text(),
                compare = attr.replace(/[\+\s]/g, '').split('').reverse(), 
                orginalTextReversed = orginalText.split('').reverse();

                for (var i = 0; i < compare.length; i++) {
                    if (orginalTextReversed[i] === ' ') {
                        totalLetters++;
                        numbers.push(orginalTextReversed[i]);
                        orginalTextReversed.splice(i, 1);
                    }
                    if (compare[i] === orginalTextReversed[i]) {
                        totalLetters++;
                        numbers.push(orginalTextReversed[i]);
                    } else {
                        numbersMatch = false;
                    }
                }
                if (numbersMatch) {
                    $(this).html(orginalText.substring(0, orginalText.length - totalLetters) + "<strong>" + numbers.reverse().join('') + "</strong>");
                }
            }
        });

    </script>

Answer №1

It's strange why the b tags aren't displaying as bold, but I've done my best to provide a solution for you.

$('li').each(function () {
    var attr = $(this).attr('data-row-internalnumber');
    var num = attr.replace(/[\+\s]/g,'');

    var finalnum = num.split('').join('\\s?').replace(/\"/,'');
    console.log(finalnum);
    var re = new RegExp("("+finalnum+")$");
    console.log(re);
    var oldval = $(this).html();
    $(this).html(oldval.replace(re,'<b>$1</b>'));
});

This code snippet targets the number in data-row-internalnumber and uses regex for search and replace within the original data content.

I hope this assistance proves helpful to you

You can view the fiddle here : http://jsfiddle.net/7y9mX/2/

In the meantime, I will continue to explore potential solutions.

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

Issue encountered when attempting to remove an element from an array using the delete method

Whenever I attempt to remove an input that has been added, an error message saying "Value is NULL" pops up. I'm looking for a solution where only the selected inputs are deleted when I click on DELETE, instead of all inputs being removed. The myFuncti ...

I aim to customize the options of a dropdown list based on the selection of another dropdown

I am looking for a way to dynamically filter employees based on the department selected. Unfortunately, my knowledge of JavaScript and Ajax is limited. <div class="pure-checkbox ml-15"> <input id="checkbox2" name="sta ...

Connecting different jQuery methods to create a chain

From my understanding of jQuery chaining, the first method in the list must complete before the next method executes. Here is an example: $.fn.reportZebraStriper = function(options) { console.log('reportZebraStriper()'); return true; } ...

Changing the value in sessionStorage does not trigger the onChange event (Next.js)

When I use a custom hook to load data from session storage into an input field, I noticed that the onChange() function doesn't trigger if I delete the entire content of the input. However, it works fine if I add or delete just one character. This issu ...

Jquery events continue to accumulate without initiating until the preceding event has completed

Looking at the code below, it essentially fades all the images to 70% within the contact class. When an image is hovered over, its opacity changes to 100%. If multiple images are hovered over or multiple hover events occur in succession, the events will st ...

Having trouble with Angular ngRoute functionality?

I'm currently working on configuring a basic Angular app. Here is my main HTML: <html ng-app="CostumerApp"> <head> <title> Customers </title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstr ...

How can I activate JQUERY when an event occurs?

I am trying to create a selection box where, upon clicking an item on the left, it will shift automatically to the right. However, I am facing issues with using triggers to achieve this functionality. Here is the code I have written. <script type="te ...

When navigating to a new route using history.push in React, it's important to ensure that the correct state is

My goal is to implement a smooth exiting animation with framer motion based on the user's current route and next destination. I specifically want the background to slide away only when transitioning from route A to route D. To achieve this, I decided ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

Python's string formatting with the '%' operator can be confusing when encountering errors such as "unsupported format character 'p'"

My current configuration looks like this: credentials={'admin_id':'user','admin_password':'pass'} credential_template='-id=%(admin_id) -pa=%(admin_password)' Upon attempting to use the code snippet: cre ...

Regular expression: Rearrange the order of matches within a capturing group

To successfully extract user identities from a smartcard, I must adhere to the pattern format: CN=LAST.FIRST.MIDDLE.0000000000 The desired result should be: FIRST.LAST If this process were implemented in my own code, it would be straightforward: # Sampl ...

When implementing auto-generated IDs in HTML forms, rely on randomly generated values for increased uniqueness

When developing a form with multiple complex controls built as Backbone views, one wants to ensure that the labels are correctly linked to the input elements. This is typically done using the "for" attribute. However, in cases where the same control needs ...

Prevent textArea from reducing empty spaces

I am facing an issue with my TextEdit application set to Plain Text mode. When I copy and paste text from TextEdit into a textarea within an HTML form, the multiple spaces get shrunk. How can I prevent the textarea from altering the spacing in the text? T ...

Different approach in Vuejs for selecting target/currentTarget in a list

I have my current configuration set up as depicted below: [{ name: "test", tags: ["aa","bb","v"] }, ...] <div class="item" v-for="item in sdList" :data-id="item.id"> <span @click="deleteTag(item, $event)" v-for="tag in item.tags ...

Differences between Jquery's Find Method and ID Attribute

In my search for efficiency, I am currently exploring ways to quickly access an element. Which method is faster: $('body').find('#elemID'); vs. var id = $('#elemID'); ...

I am curious to understand the reasons behind the occurrence of this ID problem

When I format my code like this const title = document.getElementById("title"); function handleClick() { title.style.color = "red"; } title.addEventListener("click", handleClick); everything works fine. However, if I c ...

Issue when sending PHP Papa Parse object through AJAX

I am currently working on extracting a CSV local file in PHP using AJAX and have found success with Papa Parse. However, I am facing difficulties passing the results with AJAX. Despite trying various methods such as JSON.stringify, passing only the first f ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

Does Parsley.js offer a way to configure so that the parsley-success field is not added to an input if it should be completely ignored?

Currently, I am excluding one input and adding the success class (which is fine with me) $('form').parsley({ excluded: '[data-parsley-sum-total="all"]' }); However, there are several other inputs without any validations that I do not wa ...

Two unnamed objects cannot be combined using the AsyncPipe

Currently, I am looking to implement an autocomplete feature using Angular Material in Angular 8. Below is a snippet of the code used in the TypeScript file: @Input() admins: User[]; userGroupOptions: Observable<User[]>; filterFormFG: FormGrou ...