Aaron
Aaron

Reputation: 3669

JavaScript Splitting string not working

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?

Upvotes: 2

Views: 434

Answers (3)

Strelok
Strelok

Reputation: 51481

Small mistake in your second replace. Should use a regex to replace "|". See below:

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

Upvotes: 0

Jeremy Banks
Jeremy Banks

Reputation: 129746

If you use a string as the first argument of .replace(), it will only convert the first ocurrence.

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

You need to use a regular expression with the /g global flag, like you did in the first place.

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

(| 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.

Upvotes: 5

CoderMarkus
CoderMarkus

Reputation: 1118

You need to do a global replace of the pipe bar /|/g. I believe I have encounter this in the past - by default replace in not global in JS.

Upvotes: 0

Related Questions