0

I have a URL that looks something like this after decoding using decodeURIComponent

https://secretStar.22.test.com/l/{"mode":"test","app":"revenue:app","param2":1,"loaded":{"APPLICATION@markup://revenue:app":"unique_identifier"},"pathPrefix":"","xx":1}/script22.js

Now, I would like to extract few details from this URL , for Ex:

mode = test
app =  revenue:app
param2 = 1
appMarkupRevenueApp = unique identifier
scriptName = script.js

I could have extracted it using qs params if these values were qs params. I was able to extract the information by writing a function that splits and joins and then splits again but that is not very efficient when it comes to extracting these params from more than 4k urls in a csv file.

Is there a better way to extract these? I can think of regex but I am not very familiar with that and could not get that to work.

4

1 回答 1

2

您可以通过匹配嵌入的 JSON,然后将其转换为对象来做到这一点,可能是这样的:

JSON.parse(foo.match(/({.+})[^}]+/)[1])

正则表达式通过匹配 a后跟任何内容/({.+})[^}]+/来创建一个组,然后仅当组后面跟着不是的东西时才匹配{}}

JSON 正在解析第一个匹配的组。

有一个问题,我不确定是由于您的问题有错字或与以下内容有关decodeURIComponent

在您的预期输出中,您有:

appMarkupRevenueApp = unique identifier

但是您的数据有:

"APPLICATION@markup://revenue:app":"unique_identifier"

这是完全不匹配的,不清楚哪个是正确的

小演示:

var string = 'https://secretStar.22.test.com/l/{"mode":"test","app":"revenue:app","param2":1,"loaded":{"APPLICATION@markup://revenue:app":"unique_identifier"},"pathPrefix":"","xx":1}/script22.js';

var data = JSON.parse(string.match(/({.+})[^}]+/)[1]);

for(key of Object.keys(data)) { console.log(`${key}: ${data[key]}`) }

于 2018-07-11T02:05:36.380 回答