var string = 'job_category=IT^job_description=<p><span style="font-size: 18px;">Many other html attribute's </span></p>^job_type=2^qualification=2^EQ';
//oneline string to object starts here
function get_json_from_string(x) {
var ob = {};
var a = x.split("^");
for( i = 0 ; i < a.length ; i++){
var t = a[i].split('=');
ob[ t[0] ] = t[1];
}
return ob;
}
//oneline string to object ends here
var finalOutput = get_json_from_string(string);
console.log(finalOutput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我想要字符串中的整个 job_description HTML,但是当我使用 split 时,它会分解为 = 双引号。
我怎样才能正确拆分?
对象的预期结果键值:
job_description:"<p><span style="font-size: 18px;">Many other html attributes </span></p>"
对象的当前结果键值:
job_description:"<p><span style="
//font-size: 18px;">Many other html attributes </span></p> this is cropping
注意请仔细检查我的字符串,它可以包含单引号和双引号
您可以在 '^' 上拆分,然后在 '=' 上拆分,将第一个元素作为键,然后通过 '=' 作为值将其余元素连接起来。
var string = `job_category=IT^job_description=<p><span style="font-size: 18px;">Many other html attribute's </span></p>^job_type=2^qualification=2^EQ`;
//oneline string to object starts here
function get_json_from_string(x) {
return x.split('^').reduce(function(result, token){
var subtokens = token.split('=');
result[subtokens[0]] = subtokens.slice(1).join('=');
return result;
}, {});
}
//oneline string to object ends here
var finalOutput = get_json_from_string(string);
console.log(finalOutput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句