类似的功能在JavaScript中爆炸php?

时间:2015-10-26 04:46:07

标签: javascript jquery

当我想在JavaScript中分隔我的字符串时,我遇到了问题,这是我的代码:

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

问题是当我想切片第二个字符串('json')时我也应该创建另一个切片。

我想让这段代码变得更简单,JavaScript中是否有任何函数像php中的explode函数一样?

2 个答案:

答案 0 :(得分:11)

您可以使用 split()

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

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

或使用 substring() indexOf()

var str = 'hello.json';

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

答案 1 :(得分:3)

explode的{​​{3}}:

$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(ES2015样式):

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