0

I would like to split characters into array using javascript with regex

foo=foobar=&foobar1=foobar2=

into

foo, foobar=, foobar1, foobar2=

Sorry for not being clear, let me re describe the scenario. First i would split it by "&" and want to post process it later.

str=foo=foobar=&foobar1=foobar2=
var inputvars=str.split("&")
for(i=0;i<inputvars.length;i++){
   var param = inputvars[i].split("=");
   console.log(param);
}

returns

[foo,foobar]
[]
[foobar1=foobar2]
[]

I tried to use .split("=") but foobar= got splited out as foobar.

I essentially want it to be

[foo,foobar=]
[foobar1,foobar2=]

Any help with using javascript to split first occurence of = only?

2
  • Is that really the format? where does it come from. I've never seen something with the =& like that. Other than that, it looks like part of a query string. Commented Jul 10, 2012 at 1:53
  • Can you clarify the precise rules you want to split by? Is this two levels of splitting, the first on &, then on the resulting components using =? Commented Jul 10, 2012 at 3:00

2 Answers 2

1
/^([^=]*)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')

or simpler to write but using the newer "lazy" operator:

/(.*?)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
Sign up to request clarification or add additional context in comments.

5 Comments

It return the following results ["foo=foobar=&foobar1=foobar2=", "foo", "foobar=&foobar1=foobar2="] which is not intended..
@flyclassic -- RegExp always gives the whole match as the first argument. Are the second and third the answer you need?
i know, but the results are still not what i intended LOL it should be ['foo', 'foobar=', 'foobar1', 'foobar2=']
@flyclassic - You want every other equal-sign stripped off?
thanks malvolio... you help me solve my problem already...i guess i wasnt clear earlier
0

from malvolio, i got to conclusion below

var str = 'foo=foobar=&foobar1=foobar2=';
var inputvars = str.split("&");
var pattern =  /^([^=]*)=(.*)/;
for (counter=0; counter<inputvars.length; counter++){

     var param = pattern.exec(inputvars[counter]);         
    console.log(param)
}

and results (which is what i intended)

[foo,foobar=]
[foobar1,foobar2=]

Thanks to @malvolio hint of regex Cheers

Comments

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.