5

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 ?

0

2 Answers 2

11

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)
)

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.