Luca
Luca

Reputation: 20919

Split a string on the first number occurences

I didn't get a suitable regex that enable to split such string:

72 g tocirah snaeb 101 sgge 108 g darl 111 spuc loi 32 sinihccuz

into strings basing on numbers first occurences like so:

72 g tocirah snaeb, 101 sgge, 108 g darl, 111 spuc loi, 32 sinihccuz 

How can i do that:

var str="72 g tocirah snaeb 101 sgge 108 g darl 111 spuc loi 32 sinihccuz";
var regex="/  /";
var result=str.match(regex);

Upvotes: 2

Views: 966

Answers (2)

jorgebg
jorgebg

Reputation: 6600

Use:

var result=str.replace(/ (\d+)/gm, ", $1");

Search pattern: search an space char followed by one or more numbers and capture the number.

 / (\d+)/gm

Replace: replace by a , followed by the captured number.

, $1

You can test it here: http://jsfiddle.net/2FwKF/3/

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Does this fit ?

var str="72 g tocirah snaeb 101 sgge 108 g darl 111 spuc loi 32 sinihccuz";
var regex=/\b(?=\d)/g;

var list = str.split(regex);

demo at http://jsfiddle.net/gaby/zT4QY/ (needs console)

Upvotes: 2

Related Questions