OBJECTIVE: given a string in Javascript find a set of matches via a regular expression, then split the input string by such matches.
Unlike Php, Javascript has no built in function such as
preg_split to achieve this goal.
function isplit(string, regexp, flags){
var splitter="#@#";
while(string.indexOf(splitter)!=-1){ splitter+="#"; };
flags=(flags && typeof(flags)=="string")?flags:
(!isNaN(parseFloat(flags)))?"":"g";
string=string.replace(
((typeof(regexp)=="string")?new RegExp(regexp, flags):regexp),
splitter
);
return string.split(splitter);
/*keep this comment to use freely
http://www.fullposter.com/?1 */}
INPUTS: first the string to split.
Then either a Javascript regular expression, or a string.
Then an optional third argument carrying the flags of the regular expression such as
g for retruning all ther matches or
i for case insensitive match searches).
If this argument is passed as a Number (instance: 0), it would add
no modifiers.
If not passed
at all, it defaults to a
global match detection, which is arguably exactly what is meant for such a task.
RETURNS: an array, each item a string fragment from the split input string.
CAVEATS: the function recursively builds a string making sure it is
not present within the input string, and once found it, it replaces with it the found matches; then it splits by such string.
This procedure seems more straightforward than painstakingly looping the matches grabbing per each found match the input string substrings to concatenate and making sure, at each iteration, to locate the right input string offset (matches, since they are derived from a regular expression, follow a
pattern and normally do not represent an exact set of chars; therefore, each match may differ from the other); anyway that could have been an alternative way to do it -
TIMTOWTDI, but I am not even sure if it would have been more efficient.
A similar task is achieved at
Javascript Regular Expression Match: Return The Indexes Of The Matches.