gravityboy
gravityboy

Reputation: 817

group parts of a string into an array element

If I have a string... abcdefghi and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?

var mystring = "abc+d+efghi"

output array ["a","b","cde","f","g","h","i"]

Upvotes: 2

Views: 162

Answers (3)

agent-j
agent-j

Reputation: 27913

mystring.split("\\+")

Click here for more information.

Upvotes: -2

lawnsea
lawnsea

Reputation: 6581

One way to do it:

var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);

The value of a[3] should now be 'def'. http://jsfiddle.net/rbFwR/2

Upvotes: 4

agent-j
agent-j

Reputation: 27913

You can use this expression, to produce [a][b][c+d+e][f][g][h][i].

mystring.split ("(.\+)*.")

Next, replace any + characters with empty on the resulting list.

Upvotes: 2

Related Questions