Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* The input is passed as array of query strings.
- For each field of the form, the query string contains a pair field=value.
- Within each pair, the field name and value are separated by an equals sign, '='.
- The series of pairs are separated by the ampersand, '&’.
- The question mark is used as a separator and is not part of the query string.
- SPACE is encoded as '+' or "%20". URL query string may contain another URL as value.
- Print at single line each processed string as follows: key=[value]nextkey=[another value] … etc.
- Multiple whitespace characters should be reduced to one inside value/key names,
- but there shouldn’t be any whitespaces before/after extracted keys and values.
- If a key already exists, the value is added with comma and whitespace after other values
- of the existing key in current string. */
- "use strict";
- function printArrayOfQueryStrings(args) {
- args.forEach(function(input) {
- var currentLineArr = input.split('&').filter(Boolean);
- var rowQueryObj = {};
- for (var i = 0; i < currentLineArr.length; i += 1) {
- currentLineArr[i] = currentLineArr[i].split('?').filter(Boolean);
- if (currentLineArr[i].length > 1) {
- currentLineArr[i].splice(0, 1);
- }
- currentLineArr[i] = currentLineArr[i][0];
- var pair = currentLineArr[i].split('=').filter(Boolean);
- var field = pair[0].split(/\+|%20/).filter(Boolean);
- field = field.join(' ');
- var value = pair[1].split(/\+|%20/).filter(Boolean);
- value = value.join(' ');
- if (!(field in rowQueryObj)) {
- rowQueryObj[field] = [];
- }
- if (rowQueryObj[field].indexOf(value) < 0) {
- rowQueryObj[field].push(value);
- }
- }
- var resultStr = '';
- for (var key in rowQueryObj) {
- if (rowQueryObj.hasOwnProperty(key)) {
- resultStr += key + '=[' + rowQueryObj[key].join(', ') + ']';
- }
- }
- console.log(resultStr);
- });
- }
- printArrayOfQueryStrings(['login=student&password=student']);
- printArrayOfQueryStrings(['field=value1&field=value2&field=value3',
- 'http://example.com/over/there?name=ferret']);
- printArrayOfQueryStrings(['foo=%20foo&value=+val&foo+=5+%20+203',
- 'foo=%20poo%20&value=valley&dog=wow+',
- 'url=https://softuni.bg/trainings/coursesinstances/details/1070',
- 'https://softuni.bg/trainings?trainer=nakov&course=oop&course=php']);
- printArrayOfQueryStrings(['surprise=box&surprise=pink+ribbon&flowers=red%20roses',
- 'day=birthday&day=friday%20&day=sunny+day']);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement