I am trying to split a string up but am having a problem in doing it.
My string is:
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";
I need to be able to Remove all spaces from the string (I am using the following code)
EventList = EventList.replace(/\s/g,'');
I them need to replace all | with , (comma) (I am using the following code)
EventList = EventList.replace('|',',');
I then need to split the string up by using the , (comma) (I am using the following code)
EventList = EventList.split(',');
I am trying to alart 0x2 from my string (I am using the following code)
alert(EventList[5]);
However, it is alerting 0x2|0x0 as the string and not 0x2.
My full code looks like this:
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
Anyone know where I have gone wrong?
If you use a string as the first argument of
.replace(), it will only convert the first ocurrence.You need to use a regular expression with the
/gglobal flag, like you did in the first place.(
|needs to be escaped with a\backslash in the regular expression because it has a special meaning in regular expression syntax.)I made this replacement and it displayed “0x2” as you said it should.