user3620540
user3620540

Reputation: 181

similar function explode php in javascript?

I have problem when I want to separate my string in JavaScript, this is my code :

var str= 'hello.json';
str.slice(0,4); //output hello
str.slice(6,9); //output json

the problem is when i want to slice second string ('json') I should create another slice too.

I want to make this code more simple , is there any function in JavaScript like explode function in php ?

Upvotes: 5

Views: 2166

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

You can use split()

var str = 'hello.json';
var res = str.split('.');

document.write(res[0] + ' ' + res[1])

or use substring() and indexOf()

var str = 'hello.json';

document.write(
  str.substring(0, str.indexOf('.')) + ' ' +
  str.substring(str.indexOf('.') + 1)
)

Upvotes: 11

S McCrohan
S McCrohan

Reputation: 6693

The php example for explode:

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

The Javascript equivalent (ES2015 style):

//Example 1
let pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
let pieces = pizza.split(" ");
console.log(pieces[0]);
console.log(pieces[1]);

//Example 2
let data = "foo:*:1023:1000::/home/foo:/bin/sh";
let user, pass, uid, gid, gecos, home, shell;
[user, pass, uid, gid, gecos, home, ...shell] = data.split(":");
console.log(user);
console.log(pass);

Upvotes: 3

Related Questions