1

I am parsing a multiline value from a textarea encoded in the URL:

// URL Params:
?cn=asdf%20asdf&pn=asdf%20asdf&pe=asdf%40example.com&d=asdf%0A%0Aasdf&ye=test%40example.com&c=1234&tc=true

// JAVASCRIPT
var _url = window.location.href;
var _queryParams = decodeURIComponent( _url.split('?')[1] );
var _search = _queryParams;//location.search.substring(1);
var _data = JSON.parse('{"' + decodeURI(_search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');

But I'm getting an Syntax Error: Unexpected token... error from the JSON.parse() function whenever I have a multiline text value in the d= URL param above:

&d=asdf%0A%0Aasdf

What .replace() regex pattern do I need to do to handle the line break encoding, %0A?

EDIT: I'm already successfully converting the URL params to a javascript object. The problem is that the replace([pattern match]) functions inside are choking on the mutliline text character: %0A.

tonejac
  • 1,083
  • 3
  • 18
  • 32
  • 1
    Why are you using `JSON.parse` in the first place? That's not a JSON-formatted string. – CertainPerformance Apr 18 '18 at 03:44
  • I'm converting the URL params to a json object. – tonejac Apr 18 '18 at 03:45
  • Possible duplicate of [Convert URL parameters to a JavaScript object](https://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object) – 31piy Apr 18 '18 at 04:13
  • No. It works fine already to parse into a JSON object. The problem is specifically how to successfully decode the line break code. – tonejac Apr 18 '18 at 04:28

1 Answers1

1

Parse the query string using URLSearchParams, and then use URLSearchParams's entries method to turn it into a plain Javascript object, and then stringify it to turn it into a JSON-formatted string:

const queryString = '?cn=asdf%20asdf&pn=asdf%20asdf&pe=asdf%40example.com&d=asdf%0A%0Aasdf&ye=test%40example.com&c=1234&tc=true';
const params = new URLSearchParams(queryString);
console.log(params.get('d'));
const queryObj = {};
for (const [key, val] of params.entries()) {
  queryObj[key] = val;
}
console.log(JSON.stringify(queryObj));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320