我有这个字符串:

0000000020 c90037:临时数据

我需要这个字符串:

临时:数据。

用PHP我可以这样做:

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

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


当前回答

如果你喜欢php,看看php. js - JavaScript爆炸

或者在正常的JavaScript功能中: `

var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `

其他回答

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

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

如果你喜欢php,看看php. js - JavaScript爆炸

或者在正常的JavaScript功能中: `

var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `

创建一个对象:

// create a data object to store the information below.
    var data   = new Object();
// this could be a suffix of a url string. 
    var string = "?id=5&first=John&last=Doe";
// this will now loop through the string and pull out key value pairs seperated 
// by the & character as a combined string, in addition it passes up the ? mark
    var pairs = string.substring(string.indexOf('?')+1).split('&');
    for(var key in pairs)
    {
        var value = pairs[key].split("=");
        data[value[0]] = value[1];
    }

// creates this object 
    var data = {"id":"5", "first":"John", "last":"Doe"};

// you can then access the data like this
    data.id    = "5";
    data.first = "John";
    data.last  = "Doe";

你不需要分开。你可以使用indexOf和substr:

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

但相当于爆炸的是分裂。

这是从你的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'