Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select the last 4 characters of a string using JavaScript? [duplicate]

This code chooses the highest numerical value between the data ids and adds an lime background to it. btw these numbers are hex values. my problem is that in hex values its the matter of the last 4 values but my code takes the whole characters. how can i make my code work for only the last 4 characters?

Im sorry this might be easy to solve for you but i tried over and over again and couldnt make it work.

Hex to decimal:

dc61 = 56417

dc62 = 56418

dc63 = 56419

dc64 = 56420

 maxData = $(".answers li[data-id]").get ().reduce  ( (maxObj, crrntNode) => {
 
    var idVal   = parseInt ( $(crrntNode).data("id"), 16) ; 

    if (idVal > maxObj.value) {
        maxObj.value  = idVal;
        maxObj.node   = crrntNode;
    }
    return maxObj;
  },
  {value: 0, node: null}
);
$("body").append (`<p>The highest data-id value was ${maxData.value}.</p>`)
$(maxData.node).css ("background", "lime");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question-text" class="question sp-element border-radius active">What is favorite colour?</div>
          <ul class="answers" id="answers">
            <li data-id="58b9890062279282090ddc61" class="answer sp-element border-radius active">Purple</li>
            <li data-id="58b9890062279282090ddc63" class="answer sp-element border-radius active">Blue</li>
            <li data-id="58b9890062279282090ddc64" class="answer sp-element border-radius active">Yellow</li>
            <li data-id="58b9890062279282090ddc62" class="answer sp-element border-radius active">Red</li>
          </ul>
like image 280
Nur Bar Avatar asked Dec 02 '25 09:12

Nur Bar


2 Answers

If I understand your question correctly (and I'm not sure I do), you just want to take the last 4 characters of a known string (to translate into decimal, but that wasn't your question).

In javascript, you would want to use the substring api. For example, to get the last 4 digits of an arbitrary string, you could do this:

var str = "abcdefghijklmnop";
var substr = str.substring(str.length-4, str.length);

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring

like image 90
Eric Avatar answered Dec 04 '25 23:12

Eric


Use the String.substr(startPosition, numChars) method:

var myString = "abcdefg";
console.log(myString.substr(-4, 4)); // Start 4 chars before end and take 4 chars
like image 32
Scott Marcus Avatar answered Dec 04 '25 23:12

Scott Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!