douye1876 2014-02-27 23:42
浏览 110
已采纳

在javascript中获取2个字符之间的子字符串

First of all, I tried to search it on SO but couldn't find a solution. I have a string

var str = 'a:5:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";i:3;s:1:"4";i:4;s:1:"5";}';

I want to grab all numbers between " " as an array in javascript. I tried this suggested on one of the SO questions.

console.log(str.split(/[""]/));

but this outputs

["a:5{i:0;s:1:", "1", ";i:1;:", "2", ";i:2;s:1:", "7", ";i:3;s:1:", "4", ";i:4;s:1:", "5", ";}"]

which is not exact.

Actually that above string is an array of PHP stored in MemcacheD and I am retrieving it in Node.JS and that's why I can't use json_encode or so. I am not good at Regex. So Experts please show some shine on it.

The result of above string should be an array or string like this

str = "1,2,3,4,5"; 

or an array like

array = [1,2,3,4,5];
  • 写回答

3条回答 默认 最新

  • dongma7725 2014-02-27 23:59
    关注

    So, this is a PHP serialized string. There is a version of unserialize available for javascript in the php.js project.

    So using that function.

    Javascript

    var str = 'a:5:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";i:3;s:1:"4";i:4;s:1:"5";}';
    
    console.log(unserialize(str));
    

    Output

    ["1", "2", "3", "4", "5"] 
    

    On jsFiddle

    And if you are using nodejs then you could also consider a module like php-unserialize

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?