Split a string with varying separator using jquery or javascript

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;
    }

Answers


The function split() can take a regular expression as a delimiter. Here's a sample but I'm no expert in regex so this might not be optimized.

var test = 'HH hr : MM min : SS sec';

//split by ":" or space with optional leading and trailing space
console.log(test.split(/\s?[\s:]\s?/));‚Äč
//["HH", "hr", "MM", "min", "SS", "sec"]

If I was doing this in Java, I'd compose the delimiter regex from look-aheads and look-behinds. Unfortunately, Javascript regexes don't support look-behind.

I think you need to do this the hard way. Match the string with something like

    /(.*)HH(.*)MM(.*)SS(.*)/

and then index the array returned by the matcher. If the HH / MM / SS can appear in any order, etcetera you may need a more complicated regex like this:

    /(.*?)(?:(HH|MM|SS)(.*?))*/

This is using non-eager matching and a non-capturing group. You'd have to deal with cases like "HHMMSS" (i.e. no space between the "separators") and "SS one SS" (multiple instances of the same "delimiter"). Note also that this kind of pattern is rather dangerous, since a carefully crafted input can trigger huge amounts of back-tracking.


var rx = /^(\d{2})(.*?)(\d{2})(.*?)(\d{2})(.*?)$/
var timeformat = [
    "11 hr : 22 min : 33 sec",
    "11hour:22minute:33second",
    "11h 22m 33s"
];

for (var i = 0; i < timeformat.length; i++) {
    console.log(timeformat[i])
    try {
        for (var j = 0; j < timeformat[i].match(rx).length; j++) {
            console.log('\tmatch['+j+'] = ',timeformat[i].match(rx)[j]);
        }
    } catch(e) {}
}

Need Your Help

Git fails initial push to new repo on network drive

windows git repository push

Can you help me understand why my simple startup project is not working? I am using Windows XP, with Git installed from Git-1.8.1.2-preview20130201.exe. I am using Git Bash provided with the instal...

PHP Ajax: live report of the PHP algorithm

php ajax

If I have the next algorithm in the file test.php: