我在javascript中将此文本作为字符串:
'ConversationMessage.edit({"conversation_message_id":1901,"conversation_id":154,"resource_id":112,"message":"Great :)","sent_datetime":"2017-05-22T10:04:16.583Z","message_type":0,"display_name":"Hammad Rasheed","resource_image":"http://whuntulocal.s3.amazonaws.com/1492584389-Shot.png","messageattachment_id":null,"message_id":null,"directory_name":null,"filename":null})'
我想从中提取对象。意思是我想要提取传递给ConversationMessage.edit()
的参数作为参数。
我尝试过JSON.parse()
但是失败了。
我试图str.split()
分裂")"和"("字符,但由于对象中的消息属性可以包含"而且不起作用;)"字符串,因为它目前包含"伟大的:)"。
以下是提取此字符串的HTML源代码:
<span class="message-date text-navy"><i class="fa fa-pencil text-success cursor-pointer message-edit-pencil" onclick="ConversationMessage.edit({"conversation_message_id":1901,"conversation_id":154,"resource_id":112,"message":"Great {{{{{{{","sent_datetime":"2017-05-22T10:04:16.583Z","message_type":0,"display_name":"Hammad Rasheed","resource_image":"http://whuntulocal.s3.amazonaws.com/1492584389-Shot.png","messageattachment_id":null,"message_id":null,"directory_name":null,"filename":null})"></i> Monday, 22 May 2017, 15:04 </span>
答案 0 :(得分:3)
您可以从第一个{
字符开始,以}
字符加一个字符开始,即字符串的子字符串
var a = 'ConversationMessage.edit({"conversation_message_id":1901,"conversation_id":154,"resource_id":112,"message":"Great :)","sent_datetime":"2017-05-22T10:04:16.583Z","message_type":0,"display_name":"Hammad Rasheed","resource_image":"http://whuntulocal.s3.amazonaws.com/1492584389-Shot.png","messageattachment_id":null,"message_id":null,"directory_name":null,"filename":null})'
console.log(JSON.parse(a.substring(a.indexOf('{'), a.lastIndexOf('}') + 1)));
&#13;
答案 1 :(得分:0)
我不是javascript的专家,有人可能会为您提供更好的javascript解决方案但是对于您当前的字符串,请尝试以下正则表达式,您将获得第一组的结果,
ConversationMessage\.edit\((\{.*\})\)
答案 2 :(得分:0)
简单的正则表达式应该有效:
var str = 'ConversationMessage.edit({"conversation_message_id":1901,"conversation_id":154,"resource_id":112,"message":"Great :)","sent_datetime":"2017-05-22T10:04:16.583Z","message_type":0,"display_name":"Hammad Rasheed","resource_image":"http://whuntulocal.s3.amazonaws.com/1492584389-Shot.png","messageattachment_id":null,"message_id":null,"directory_name":null,"filename":null})';
var objString = /^ConversationMessage\.edit\((.*)\)$/.exec(str);
var obj = JSON.parse(objString[1]);
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }