Unable to split String element and append to <div>

Funtionality:

I have a String A,4.0,00:04. The main purpose to Split the String is to append the value of 00:04 to the following div of "min" and "sec", hence, i will need to further split the value of 00:04 such that when i append the value it will be displayed as "00 min" "04 sec".

Issue:

At this point I am unable to to split further than the "," and when i do my console.log on the Split string, it will return the individual String element of A| 4.0| 00:04.

However, at this point, I do not know how to proceed further to take out the individual element of "00" and "04" to append to the "min" & "sec" div tag.

Please help.

var data = 'A,4.0,00:04';
console.log("BestTime: " + data);
//When I consolelog BESTTIME, it will return the element of (A, 4.0, 00:04)

var TimerList = data.split(",");
console.log("TimerList: " + TimerList[0] + "|" + TimerList[1] + "|" + TimerList[2]);

//TimerList[0] => A //Not What I want to append to div tag
//TimerList[1] => 4.0 // Not What I want to append to div tag
//TimerList[2] => 00:04 //Need to futher split this so that I can append 00 to Game_BestTimer_Minute & 04 to Game_BestTimer_Second

//append BEST GAME TIME to SCOREBOARD
$("#Game_BestTimer_Minute").html(TimerList[2]);
$("#Game_BestTimer_Second").html(TimerList[2]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Game_BestTimer_Minute" style="font-family:'Avenir';"></div>

<div id="Game_BestTimer_Second" style="font-family:'Avenir';"></div>

Answers 1

  • You can use String.prototype.match() with RegExp /\d+(?=:)|\d+$/g to match one or more digit characters followed by ":" or digits at end of string to get array containing ["00", "04"].

    Use multiple selectors at jQuery() to make single call to .html(function)

    var data = 'A,4.0,00:04';
    var TimerList = data.match(/\d+(?=:)|\d+$/g);
    
    console.log(TimerList);
    
    $("#Game_BestTimer_Minute, #Game_BestTimer_Second")
    .html(function(index, _) {
      return TimerList[index]
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <div id="Game_BestTimer_Minute" style="font-family:'Avenir';"></div>
    <div id="Game_BestTimer_Second" style="font-family:'Avenir';"></div>


Related Articles