我有这个字符串:

0000000020 c90037:临时数据

我需要这个字符串:

临时:数据。

用PHP我可以这样做:

$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];

我如何有效地爆炸一个字符串在JavaScript的方式,它在PHP工作?


当前回答

所以我知道这篇文章很老了,但我想我不妨添加一个多年来帮助我的功能。为什么不像上面提到的那样使用split重做爆炸函数呢?就是这样:

function explode(str,begin,end)
{
   t=str.split(begin);
   t=t[1].split(end);
   return t[0];
}

如果您试图获取两个值之间的值,则此函数工作得很好。例如:

data='[value]insertdataherethatyouwanttoget[/value]';

如果您对从两个[值]“标记”之间获取信息感兴趣,可以使用如下所示的函数。

out=explode(data,'[value]','[/value]');
//Variable out would display the string: insertdataherethatyouwanttoget

但是,假设您没有像上面显示的例子那样方便的“标签”。不管。

out=explode(data,'insert','wanttoget');
//Now out would display the string: dataherethatyou

想看看实际情况吗?请点击这里。

其他回答

试试这个:

arr = str.split (":");
String.prototype.explode = function (separator, limit)
{
    const array = this.split(separator);
    if (limit !== undefined && array.length >= limit)
    {
        array.push(array.splice(limit - 1).join(separator));
    }
    return array;
};

应该完全模仿PHP的爆炸()函数。

'a'.explode('.', 2); // ['a']
'a.b'.explode('.', 2); // ['a', 'b']
'a.b.c'.explode('.', 2); // ['a', 'b.c']

看起来你想分开

var str = "helloword~this~is~me";
var exploded = str.splice(~);

爆炸变量将返回数组,你可以访问数组中的元素,访问它true explosive [nth],其中nth是你想要得到的值的下标

只是对神经病brm的回答的一点补充(他的版本在IE中不能工作<=8)。 此代码是跨浏览器兼容的:

function explode (s, separator, limit)
{
    var arr = s.split(separator);
    if (limit) {
        arr.push(arr.splice(limit-1, (arr.length-(limit-1))).join(separator));
    }
    return arr;
}