开发者

Javascript Equivalent to PHP Explode()

开发者 https://www.devze.com 2023-02-01 01:41 出处:网络
I have this string: 0000000020C90037:TEMP:data I need this string: TEMP:data. W开发者_如何学Pythonith PHP I would do this:

I have this string:

0000000020C90037:TEMP:data

I need this string:

TEMP:data.

W开发者_如何学Pythonith PHP I would do this:

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

How do I effectively explode a string in JavaScript the way it works in PHP?


This is a direct conversion from your PHP code:

//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'


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;
};

Should mimic PHP's explode() function exactly.

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


You don't need to split. You can use indexOf and substr:

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

But the equivalent to explode would be split.


Looks like you want split


Try this:

arr = str.split (":");


create's an object :

// 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";


Use String.split

"0000000020C90037:TEMP:data".split(':')


If you like php, take a look at php.JS - JavaScript explode

Or in normal JavaScript functionality: `

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


console.log(('0000000020C90037:TEMP:data').split(":").slice(1).join(':'))

outputs: TEMP:data

  • .split() will disassemble a string into parts
  • .join() reassembles the array back to a string
  • when you want the array without it's first item, use .slice(1)


With no intentions to critique John Hartsock, just in case the number of delimiters may vary for anyone using the given code, I would formally suggest to use this instead...

var mystr = '0000000020C90037:TEMP:data';
var myarr = mystr.split(":");
var arrlen = myarr.length;
var myvar = myarr[arrlen-2] + ":" + myarr[arrlen-1];


var str = '0000000020C90037:TEMP:data';    // str = "0000000020C90037:TEMP:data"
str = str.replace(/^[^:]+:/, "");          // str = "TEMP:data"


Just a little addition to psycho brm´s answer (his version doesn't work in IE<=8). This code is cross-browser compatible:

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;
}


I used slice, split and join You can just write one line of code

      let arrys = (str.split(":").slice(1)).join(":");


So I know that this post is pretty old, but I figured I may as well add a function that has helped me over the years. Why not just remake the explode function using split as mentioned above? Well here it is:

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

This function works well if you are trying to get the values between two values. For instance:

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

If you were interested in getting the information from between the two [values] "tags", you could use the function like the following.

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

But let's say you don't have those handy "tags" like the example above displayed. No matter.

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

Wana see it in action? Click here.


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

the exploded variable will return array and you can access elements of the array be accessing it true exploded[nth] where nth is the index of the value you want to get


try like this,

ans = str.split (":");

And you can use two parts of the string like,

ans[0] and ans[1]


If you want to defined your own function, try this:

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
}

Taken from: http://locutus.io/php/strings/explode/

0

精彩评论

暂无评论...
验证码 换一张
取 消