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>