JavaScript Equivalent to PHP Explode()

Javascript Equivalent to PHP Explode()

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'

Looking for JavaScript analogues for PHP's `explode` and `implode` functions

JavaScript has the String.split and Array.join functions.

String.split is a lot like php's explode. It takes a single parameter: a string delimiter to split on. In your case you could swap out explode for split:

function getHashtags(str) {
let words = str.split(' ');
let hashtags = [];
words.forEach((word) => {
if (word[0] === '#') {
hashtags.push(word);
}
});
}

For implode, Array.join is very similar. This function also takes a single (optional) parameter: a string to place between each element of the array when they are joined together. If this parameter is omitted, the elements of the array are joined together without anything in between. You could swap out your call to implode for join.

However, I should point out that you do not need to use an array for this. Since the desired result is a string, why not just use string concatenation to solve this, without using an array first? Something like this:

function generateSentence() {
let subjects = ['He', 'She', 'John', 'Jane', 'The girl', 'The boy', 'The dog'];
let verbs = ['ran', 'jumped', 'ate', 'danced', 'played', 'laughed'];
let adverbs = ['quickly', 'happily', 'merrily', 'slowly'];

const random = (length) => Math.floor(Math.random()*length);
let result = "";
result += subjects[random(subjects.length)] + " ";
result += verbs[random(verbs.length)] + " ";
result += adverbs[random(adverbs.length)] ".";

return result;
}

Javascript - explode equivilent?

const string = "123|34|23|2342|234";
const arr = string.split('|');

for(let i in arr){
if(arr[i] == 123) alert(arr[i]);
}

Or:

for(let i in arr){
if(arr[i].indexOf('123') > -1) alert(arr[i]);
}

Or:

arr.forEach((el, i, arr) => if(arr[i].indexOf('123') > -1) alert(arr[i]) }

Or:

arr.forEach((el, i, arr) => if(el == '123') alert(arr[i]) }

Or:

const arr = "123|34|23|2342|234".split('|')

if(arr.some(el=>el == "123")) alert('123')

More information on string and Array memeber functions.

similar function explode php in javascript?

You can use split()

var str = 'hello.json';var res = str.split('.');
document.write(res[0] + ' ' + res[1])

PHP equivalent of list and explode in javascript

var values = "1, 2, 3".split(", ");
var keys = ["Id", "Iduser", "Idmany"];
var final = {};

for(var i = 0; i < values.length; i++){
final[keys[i]] = values[i];
}

Of course, at the expense of readability you could do all this in the for statement:

for(var i = 0, values = "1, 2, 3".split(", "), keys = ["Id", "Iduser", "Idmany"], final = {}; i < values.length; i++){
final[keys[i]] = values[i];
}

The variables can then be accessed as follows:

alert(final.Id);
alert(final.Iduser);
alert(final.Idmany);

How to match PHP's explode(';',$s,3) to s.split(';',3) in JavaScript?

Alright, I created 4 alternative versions of the PHP split string algorithm, along with the two provided by @hanshenrik, and did a basic benchmark on them:

function explode1(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = [];
var lastIndex = -1;
var index = 0;
for (var i = 0; i < limit; i++) {
index = str.indexOf(delimiter, lastIndex + 1);
if (i == limit - 1) {
a.push(str.substring(lastIndex + 1));
} else {
a.push(str.substring(lastIndex + 1, index));
}
lastIndex = index;
}
return a;
}

function explode2(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = str.split(delimiter);
var ret = a.slice(0, limit - 1);
ret.push(a.slice(limit - 1).join(delimiter));
return ret;
}

function explode3(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = s.split(delimiter, limit - 1);
var index = 0;
for (var i = 0; i < limit - 1; i++) {
index = s.indexOf(delimiter, index + 1);
}
a.push(str.substring(index + 1));
return a;
}

function explode4(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = str.split(delimiter, limit - 1);
a.push(str.substring(a.join(delimiter).length + 1));
return a;
}

function explode5(delimiter, string, limit) {
// discuss at: http://locutus.io/php/explode/
// original by: Kevin van Zonneveld (http://kvz.io)
// example 1: explode(' ', 'Kevin van Zonneveld')
// returns 1: [ 'Kevin', 'van', 'Zonneveld' ]

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
}

function explode6(delimiter, string, limit) {
var spl = string.split(delimiter);
if (spl.length <= limit) {
return spl;
}
var ret = [],i=0;
for (; i < limit; ++i) {
ret.push(spl[i]);
}
for (; i < spl.length; ++i) {
ret[limit - 1] += delimiter+spl[i];
}
return ret;
}

var s = 'Mark Twain,1879-11-14,"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."'
console.log(s);

console.time('explode1');
var a1 = explode1(',', s, 3);
//console.log(a1);
console.timeEnd('explode1');

console.time('explode2');
var a2 = explode2(',', s, 3);
//console.log(a2);
console.timeEnd('explode2');

console.time('explode3');
var a3 = explode3(',', s, 3);
//console.log(a3);
console.timeEnd('explode3');

console.time('explode4');
var a4 = explode4(',', s, 3);
//console.log(a4);
console.timeEnd('explode4');

console.time('explode5');
var a5 = explode5(',', s, 3);
//console.log(a5);
console.timeEnd('explode5');

console.time('explode6');
var a6 = explode6(',', s, 3);
//console.log(a6);
console.timeEnd('explode6');

The two best-performing algorithms was explode4 principally, with explode3 a close second in multiple iterations of the benchmark:

$ node explode1.js && node explode2.js && node explode3.js && node 
explode4.js && node explode5.js && node explode6.js
explode1: 0.200ms
explode2: 0.194ms
explode3: 0.147ms
explode4: 0.183ms
explode5: 0.341ms
explode6: 0.162ms

You can run your own benchmarks, but with my tests I can confirm that splitting an array by n - 1 and then getting an index from joining the resulting array is the fastest algorithm matching explode in PHP.

EDIT: It turns out that the garbage collector biased how each successive function was measured, so I split them off into their own individual files and re-ran the benchmarking a few times. It seems explode3 is the best performing, not explode4, but I won't make a decision that I'm not completely sure of.

Is explode equivalent to implode when using the same parameter?

If $string is a string, yes.

Otherwise type conversion may occur:

implode(",", explode(",", 0))

This will result in "0" thus $string !== normalize($string) but $string == normalize($string) still holds true.

is there any function like php explode in jquery?

The plain JavaScript String object has a split method.

'path1/path2'.split('/')

'http://www.somesite.com/#path1/path2'.split('#').pop().split('/')

-> ['path1', 'path2']

However, for the second case, it's generally not a good idea to do your own URL parsing via string or regex hacking. URLs are more complicated than you think. If you have a location object or an <a> element, you can reliably pick the parts of the URL out of it using the protocol, host, port, pathname, search and hash properties.



Related Topics



Leave a reply



Submit