Similar function explode php in javascript?

I have a 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 cut the second line ('json'), I have to create another slice.

I want to make this code simpler, is there any function in JavaScript, for example, explode function in php?

+5
source share
2 answers

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) ) 
+11
source

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

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); 
+3
source

Source: https://habr.com/ru/post/1234500/


All Articles