Getting an array of matches and simple strings from a JavaScript regular expression

I often want to parse a string with a regex and find all matches plus all strings that don't match, and all interspersed in their original order, for example.

var parsed = regexParse(/{([^}]+)}/g, 'Hello {name}, you are {age} years old');

And therefore it parsedwill contain:

0 : "Hello "
1 : match containing {name}, name
2 : ", you are "
3 : match containing {age}, age
4 : " years old"

Is there anything in JavaScript (or some kind of widely used library) that resembles this function regexParse? I wrote my own version, but it seems so obvious that I suspiciously that there should already be a “standard” way to do this:

var regexParse = function(rx, str) {
  var nextPlain = 0, result = [], match;
  rx.lastIndex = 0;
  for (;;) {
    match = rx.exec(str);
    if (!match) {
      result.push(str.substr(nextPlain));
      break;
    }
    result.push(str.substr(nextPlain, match.index - nextPlain));
    nextPlain = rx.lastIndex;
    result.push(match);
  }
  return result;
};

Update

, , , . , ?

( IE9 Chrome ) , split , , - , - , .. , - .

:

'{x}'.split(/{([^}]+)}/g)

:

["", "x", ""]

, , , , ( )!

ES5 map, forEach filter. , regexParse, typeof i == 'string , .

split , , ES5 , , , ( ) ( ). , , :

var ar = '{greeting} {name}, you are {age} years old'.split(/{([^}]+)}/g);

ar :

["", "greeting", " ", "name", ", you are ", "age", " years old"]

:

ar.filter(function(s, i) { return i % 2 != 0; });

>>> ["greeting", "name", "age"]

, :

ar.filter(function(s, i) { return (i % 2 == 0) && s; });

>>> [" ", ", you are ", " years old"]
+3
1

, split() :

var myString = "Hello 1 word. Sentence number 2.";
var splits = myString.split(/(\d)/); // Hello ,1, word. Sentence number ,2, .
+6

All Articles