Javascript 等价于 PHP Explode()

IT技术 javascript php string
2021-01-14 04:54:22

我有这个字符串:

0000000020C90037:TEMP:数据

我需要这个字符串:

温度:数据。

使用 PHP 我会这样做:

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

如何explode像在 PHP 中那样有效地在 JavaScript 中创建字符串?

6个回答

这是从您的 PHP 代码的直接转换:

//Loading the variable
var mystr = '0000000020C90037:TEMP:data';

//Splitting it with : as the separator
var myarr = mystr.split(":");

//Then read the values from the array where 0 is the first
//Since we skipped the first element in the array, we start at 1
var myvar = myarr[1] + ":" + myarr[2];

// Show the resulting value
console.log(myvar);
// 'TEMP:data'
+1:没错;这里是从MDN链接:developer.mozilla.org/en/JavaScript/Reference/Global_Objects/...和“相反”方向,所以 PHP implode() 等价物是 myArray.join(':'): developer.mozilla.org/en/JavaScript/Reference/Global_Objects/...
2021-03-16 04:54:22
我添加了一个代码注释来清除数组 [0] 的东西,可能会让新手感到困惑......
2021-03-18 04:54:22
注意split(delimiter,limit)的 limit 参数与explode($delimiter,$string,$limit)的 limit 参数不同。示例:explode('.','1.2.3.4',3) === array('1','2','3.4')- 在 Javascript 中,您将获得:'1.2.3.4'.split('.',3) === ['1', '2', '3']. 任何人都知道如何轻松复制 PHP 的方法?
2021-03-20 04:54:22
@Herr Kaleun ......这是可以理解的......但是OP想要数组中的最后两个项目。
2021-04-07 04:54:22
需要注意的是数组从[0]开始
2021-04-12 04:54:22

你不需要分开。您可以使用indexOfsubstr

str = str.substr(str.indexOf(':')+1);

但相当于explode将是split

可能有人认为你很狡猾。有时你必须解释一切。例如,“您的问题最好通过 'indexOf' 来解决……但是 'split' 从字面上回答了您的问题。”
2021-03-15 04:54:22
Downvoter:“你怎么提供更简单、更高效的解决方案,而不是验证我的先入之见?”
2021-03-31 04:54:22
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 的 expand() 函数。

'a'.explode('.', 2); // ['a']
'a.b'.explode('.', 2); // ['a', 'b']
'a.b.c'.explode('.', 2); // ['a', 'b.c']
多么简单而优雅的解决方案,我希望这是公认的回应。
2021-03-24 04:54:22
就我所见,作为唯一一个提供与 PHP 的爆炸功能等效实际功能(根据原始问题),我感到荣幸
2021-04-13 04:54:22

看起来你想分开

试试这个:

arr = str.split (":");