我有这个字符串:
0000000020 c90037:临时数据
我需要这个字符串:
临时:数据。
用PHP我可以这样做:
$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];
我如何有效地爆炸一个字符串在JavaScript的方式,它在PHP工作?
我有这个字符串:
0000000020 c90037:临时数据
我需要这个字符串:
临时:数据。
用PHP我可以这样做:
$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];
我如何有效地爆炸一个字符串在JavaScript的方式,它在PHP工作?
当前回答
这是从你的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'
其他回答
所以我知道这篇文章很老了,但我想我不妨添加一个多年来帮助我的功能。为什么不像上面提到的那样使用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
想看看实际情况吗?请点击这里。
console.log (0000000020 c90037:临时:数据).split(“:”).slice (1) . join (': '))
输出:临时数据
.split()将把字符串分解成多个部分 .join()将数组重新组装为字符串 当你想要数组没有第一项时,使用.slice(1)
试试这个:
arr = str.split (":");
如果你想定义你自己的函数,试试这个:
function explode (delimiter, string, limit) {
if (arguments.length < 2 ||
typeof delimiter === 'undefined' ||
typeof string === 'undefined') {
return null
}
if (delimiter === '' ||
delimiter === false ||
delimiter === null) {
return false
}
if (typeof delimiter === 'function' ||
typeof delimiter === 'object' ||
typeof string === 'function' ||
typeof string === 'object') {
return {
0: ''
}
}
if (delimiter === true) {
delimiter = '1'
}
// Here we go...
delimiter += ''
string += ''
var s = string.split(delimiter)
if (typeof limit === 'undefined') return s
// Support for limit
if (limit === 0) limit = 1
// Positive limit
if (limit > 0) {
if (limit >= s.length) {
return s
}
return s
.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
])
}
// Negative limit
if (-limit >= s.length) {
return []
}
s.splice(s.length + limit)
return s
}
摘自:http://locutus.io/php/strings/explode/
var str = '0000000020C90037:TEMP:data'; // str = "0000000020C90037:TEMP:data"
str = str.replace(/^[^:]+:/, ""); // str = "TEMP:data"