1

The following jQuery code:

 $.param({                                        
                  Parts: [{ hasLabel: "label", hasType: "type", hasIndex : 1 }],
                  LastKey : "LastKey",
                  Term : "Term"                             
         })

gives the following output:

 "Parts%5B0%5D%5BhasLabel%5D=label&Parts%5B0%5D%5BhasType%5D=type&Parts%5B0%5D%5BhasIndex%5D=1&LastKey=LastKey&Term=Term"

which decodes to (using decodeURI()) :

 "Parts[0][hasLabel]=label&Parts[0][hasType]=type&Parts[0][hasIndex]=0&LastKey=LastKey&Term=Term"

However, the default model binder in MVC expects the following:

 "Parts[0].hasLabel=label&Parts[0].hasType=type&Parts[0].hasIndex=0&LastKey=LastKey&Term=Term"

I'm looking for a Javascript Regex to coerce the encoded string into a (still encoded) string , but one that decodes to the correct model binding convention.

1 Answer 1

2

The following should do the trick:

var params = "Parts[0][hasLabel]=label&Parts[0][hasType]=type&Parts[0][hasIndex]=0&LastKey=LastKey&Term=Term";
var mvcParams = params.replace(/\[([^0-9]+)\]/g,'.$1');

EDIT:

To work on an encoded string do the following:

var params = "Parts%5B0%5D%5BhasLabel%5D=label&Parts%5B0%5D%5BhasType%5D=type&Parts%5B0%5D%5BhasIndex%5D=1&LastKey=LastKey&Term=Term";
var mvcParams = params.replace(/%5b([^0-9]+)%5d/gi,'.$1');
Sign up to request clarification or add additional context in comments.

6 Comments

cr@p, really sorry but I just realized that I actually needed this to work on the encoded string, aka the return value of encodeURI("Parts[0][hasLabel]=label&Parts[0][hasType]=type&Parts[0][hasIndex]=0&LastKey=LastKey&Term=Term"). Need to coerce the result of that into something such that decodeURI(result) == "Parts[0].hasLabel=label&Parts[0].hasType=type&Parts[0].hasIndex=0&LastKey=LastKey&Term=Term"
I've just tested it and it works! How it works? with your expression, shouldn't be replaced everything between [ ]? what's the meaning of '.$1' (a link to the definition will be apreciated)...
@parliament: if you call encodeURI on the variable mvcParams above you will get the desired result
@ESt3b4n: go here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… and search for the description of $n
Yes but thats just unneccesary processing because i have to send the encoded version so I would have to do encodeURI(decodeURI($.param(data)).replace(regex)) instead of $.param(data).replace(regex)
|

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.