how to get specific value from a string

Viewed 188

have this String "name=jack&age=22&true&red" and i want to get all the value as sperate String i can get the first value by this but don't know how to get the other

String text = "name=jack&age=22&true&red" ;
var splitText = text.split("&") ; // [name=jack, age=22, true, red]
var firstValue= splitText.first ;  // name=jack
4 Answers

By index:

splitText[1] // age=22
splitText[2] // true
splitText[3] // red

If you want to get what is after the equal sign as a whole chunk (the value of the key 'name' is jack) you can use this code:

void main() {
  String text = "name=jack&age=22&true&red" ;
  // This regex matches any alphanumeric followed by a '=' and those preceded by a '&'. 
  RegExp exp = new RegExp("&([A-Za-z0-9]*=)|([A-Za-z0-9]*=)");
  final splitted = text.split(exp);
  splitted.removeWhere((item)=> item.isEmpty);
  print(splitter); // Outputs: [jack, 22&true&red]
 }

I'm not sure whether this could be an answer. Why don't you try to use an index?

splitText[1] // age=22
splitText[2] // true
..

This looks a lot like query parameters from a Uri. If so, run this in dartpad to see an easy way to do this:

void main() {
  var u = Uri(query: 'name=jack&age=22&true&red');
  var qp = u.queryParametersAll;
  print(qp);
}

Output:

{name: [jack], age: [22], true: [], red: []}
Related