2

我正在尝试拆分字符串,但在执行此操作时遇到问题。

我的字符串是:

var EventList = "0x0,0x1,0x1 | 0x0,0xff,0x2 | 0x0,0x1,0x1 | 0x0,0x1,0x1 | 0x0,0xff,0x5 | 0x0,0xff,0x7 | 0x0,0xff,0x3 | 0x0,0xff,0x6";

我需要能够从字符串中删除所有空格(我正在使用以下代码)

EventList = EventList.replace(/\s/g,'');

我他们需要全部更换| with , (comma) (我使用下面的代码)

EventList = EventList.replace('|',',');

然后我需要使用 , (逗号)拆分字符串(我正在使用以下代码)

EventList = EventList.split(','); 

我正在尝试从我的字符串中发出 0x2 警报(我正在使用以下代码)

警报(事件列表 [5]);

但是,它警告 0x2|0x0 作为字符串而不是 0x2。

我的完整代码如下所示:

var EventList = "0x0,0x1,0x1 | 0x0,0xff,0x2 | 0x0,0x1,0x1 | 0x0,0x1,0x1 | 0x0,0xff,0x5 | 0x0,0xff,0x7 | 0x0,0xff,0x3 | 0x0,0xff,0x6";
EventList = EventList.replace(/\s/g,''); // replace any spaces in EventList
EventList = EventList.replace('|',',');  // replace any | with ,
EventList = EventList.split(',');       // Split EventList

alert(EventList[5]); // should alert 0x2 but it alerts 0x2|0x0

有谁知道我哪里出错了?

4

3 回答 3

5

如果您使用字符串作为 的第一个参数.replace(),它只会转换第一次出现。

var EventList = "a|b|c|d";
EventList = EventList.replace('|',',');
alert("a,b|c|d"); // displays "a,b|c|d"

您需要使用带有/g全局标志的正则表达式,就像您一开始所做的那样。

EventList = EventList.replace(/\|/g,',');  // replace any | with ,

(|需要在正则表达式中使用\反斜杠进行转义,因为它在正则表达式语法中具有特殊含义。)

我做了这个替换,它显示“0x2”,正如你所说的那样。

于 2012-08-20T01:46:54.370 回答
0

您需要对管道栏 /|/g 进行全局替换。我相信我过去曾遇到过这种情况 - 默认情况下,在 JS 中替换不是全局的。

于 2012-08-20T01:46:28.480 回答
0

第二次更换的小错误。应该使用正则表达式替换“|”。见下文:

var EventList = "0x0,0x1,0x1 | 0x0,0xff,0x2 | 0x0,0x1,0x1 | 0x0,0x1,0x1 | 0x0,0xff,0x5 | 0x0,0xff,0x7 | 0x0,0xff,0x3 | 0x0,0xff,0x6";
EventList = EventList.replace(/\s/g,''); // replace any spaces in EventList
EventList = EventList.replace(/\|/g,',');  // replace any | with ,
EventList = EventList.split(',');       // Split EventList

alert(EventList[5]); // alerts 0x2
于 2012-08-20T01:48:39.873 回答