xgqfrms / FEIQA

FEIQA: Front End Interviews Question & Answers
https://feiqa.xgqfrms.xyz
MIT License
7 stars 0 forks source link

text to JSON #99

Open xgqfrms opened 4 years ago

xgqfrms commented 4 years ago

text to JSON

https://www.cnblogs.com/xgqfrms/p/13283680.html

https://repl.it/@xgqfrms/js-relpace-n#readme.md

https://www.cloudflare.com/cdn-cgi/trace


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-07-01
 * @modified
 *
 * @description text to JSON & js replace \n
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/13283680.html
 * @link https://repl.it/@xgqfrms/js-relpace-n#readme.md
 * @link https://www.cloudflare.com/cdn-cgi/trace
 *
 */

const log = console.log;

const text = `
fl=12f405
h=www.cloudflare.com
ip=240e:e0:5a14:4e00:84de:3d45:c099:7362
ts=1594452831.277
visit_scheme=https
uag=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4198.2 Safari/537.36
colo=LAX
http=http/2
loc=CN
tls=TLSv1.3
sni=plaintext
warp=off
`;

let str = text.trim();

// log(`str`, str)

// js replace \n ???
// str = str.replace(/\n/ig, `šŸš€`);
// str = str.replace(/\r\n/ig, `šŸš€`);
str = str.replace(/(?:\r\n|\r|\n)/ig, `šŸš€`);
// str = str.replace(/(?:\r\n|\r|\n)/ig, `XYZ`);

// log(`str`, str, typeof str)

let arr = str.split(`šŸš€`);
// arr = str.split(`šŸš€`).join();
// arr = str.split(`=`);

// log(`arr 2`, arr)

const obj = {};

let result = arr.map((item, i) => {
  // log(`item`, item);
  // return item.trim().replace(/\\n/ig, ``);
  const [k, v] = item.trim().split(`=`);
  log(`k, v`, k, v);
  obj[k] = v;
});

// log(`result `, result)

// log(`json`, obj);
log(`json`, JSON.stringify(obj, null, 4));
log(`json`, JSON.parse(JSON.stringify(obj, null, 4)));

js replace \n

// 1. regex
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');

// split & join

https://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-elements

xgqfrms commented 4 years ago

https://repl.it/@xgqfrms/js-relpace-n

xgqfrms commented 4 years ago

https://github.com/xgqfrms/FEIQA/issues/52