2

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"]

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

I threw some alerts in there and the plus sign is still there? alert(s.match(/([^+])(?:\+[^+])*/g));;;; alert(s.replace(/\+/g, '')); alert(s[4]);;;
I didn't assign the result back to s, just dumped it to the console. I can see now that my reuse of the s name was confusing. Updated.
Is there anyway to do this without console.log?
2

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.

1 Comment

How would you replace any + characters with empty on the resulting list.
-2
mystring.split("\\+")

Click here for more information.

3 Comments

This would give ['abc','d','efghi']
won't that just split it into 3 sections?
The answer for this should have 7 array elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.