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

JS or Prototype: Break string into two variables

本文关键字:变量 两个 Prototype 字符串 JS      更新时间:2023-09-26

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

成果1:-能够创建2D动画,用作交互式媒体产品的一部分

我想得到"-"之前的所有内容并将其放入一个变量,以及"-"之后的所有内容,并将其置于另一个变量。所以输出是这样的:

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

感谢

(还有人知道我会如何从下面的选择器中删除标题标签吗?

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

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

  1. 去掉冒号(:)
  2. 去掉仪表板周围的多余空间(-)

因此:

var tokens = s.split(/:'s*-'s*/);
// tokens[0] will be the first part
// tokens[1] the second
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."

Fiddle:http://jsfiddle.net/maniator/VqcPJ/

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

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