We can use javascript split method to split a string into an array of substrings. Example:
var timeformat="HH:MM:SS";
var timeformatarray=timeformat.split(":");
Is there a simple method to split a string if separator is not constant. Actually, I have to split timeformat that could come in any format like:
var timeformat="HH hr : MM min : SS sec";
var timeformat="HHhour:MMminute:SSsecond";
var timeformat="HHh MMm SSs";
Only constant would be HH, MM and SS. Timeformat is an option for the user to specify what is the format of the time that they want to display. "HH", "MM" and "SS" are constant text (Not numbers), these three are fixed constants that won't change. Only thing that could change is the suffix and the separator in the timeformat string as shown in examples above.
I want a method to split timeformat string into an array so that I can work on it. I want the result be:
timeformat[0] = "HH"
timeformat[1] = " hr : " <- with spaces (if any)
timeformat[2] = "MM"
timeformat[3] = " min : "
timeformat[4] = "SS"
timeformat[5] = " sec"
With this array, I will format the time and add respective suffix and separators. I tried various methods, using regex and looping through each character, but they were not efficient and straight. Thanks for the help in advance.
Solution:
I was able to resolve the issue by creating a method that works on the formatstring using regex, split and arrays. I am sure there would be much better solution but I couldn't get any so here is my solution to the problem. I would thank Stephen C
for the direction on regex.
function GetTimeFormatArray(timeformatstring){
var timesuffixes = timeformatstring.split(/HH|MM|SS/);
timesuffixes= $.grep(timesuffixes,function(n){
return(n);
});
var pattern = timesuffixes.join('|');
var timeprefixes = timeformatstring.split(new RegExp(pattern));
timeprefixes = $.grep(timeprefixes,function(n){
return(n);
});
var timeFormatArray = [];
for(var i = 0; i < timesuffixes.length; i++){
timeFormatArray.push(timeprefixes[i]);
timeFormatArray.push(timesuffixes[i]);
}
return timeFormatArray;
}