JS或Prototype:将字符串分解为两个变量

时间:2011-06-17 16:03:08

标签: javascript string prototypejs

假设我有一堆字符串,它们遵循与此相同的结构:

Outcome 1: - Be able to create 2D animations for use as part of an interactive media product.

我希望在' - '之前获取所有内容并将其放入一个变量中,并将所有内容放在' - '之后并将其放入另一个变量中。因此输出如此:

$1 = "Outcome 1";
$2 = "Be able to create 2D animations for use as part of an interactive media product.";

由于

(也有人知道我将如何从以下选择器中删除标题标签吗?

  $$('span[title]').each(function(element) {
});

3 个答案:

答案 0 :(得分:0)

var string = "Outcome 1: - Be able to create 2D animations for use as part of an interactive media product."

var strArr = string.split("-");

结果:

strArr[0] == "Outcome 1: "
strArr[1] == " Be able to create 2D animations for use as part of an interactive media product."

小提琴:http://jsfiddle.net/maniator/VqcPJ/

答案 1 :(得分:0)

这个正则表达式将删除第一个元素上的尾部冒号以及破折号周围的任何空格:

var parts = str.split(/\s*:\s*-\s*/);
parts; // => ['Outcome 1', 'Be able to create...']

答案 2 :(得分:0)

您可以使用正则表达式拆分字符串。在您的情况下,您想要:

  1. 摆脱冒号(:)
  2. 摆脱破折号周围的额外空间( - )
  3. 所以:

    var tokens = s.split(/:\s*-\s*/);
    // tokens[0] will be the first part
    // tokens[1] the second